Skip to content

Commit 53a8eb8

Browse files
committed
fix: 404 intead of 401/un authorised for non existant api
1 parent c0ad878 commit 53a8eb8

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/server.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,16 @@ const server = fastify({logger: true});
2626
/* Adding an authentication hook to the server. A hook is a function that is called when a request is made to
2727
the server. */
2828
server.addHook('onRequest', (request, reply, done) => {
29-
if (!isAuthenticated(request)) {
29+
const routeExists = server.hasRoute({
30+
url: request.raw.url,
31+
method: request.raw.method
32+
// constraints: { version: '1.0.0' } specify this if you are doing something custom
33+
});
34+
35+
if (!routeExists) {
36+
reply.code(HTTP_STATUS_CODES.NOT_FOUND);
37+
done(new Error('Not Found'));
38+
} else if (!isAuthenticated(request)) {
3039
reply.code(HTTP_STATUS_CODES.UNAUTHORIZED);
3140
done(new Error('Wrong key'));
3241
} else {

test/integration/hello.spec.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,14 @@ describe('Integration Tests for hello api', function () {
3737
"message": "Wrong key",
3838
"statusCode": 401});
3939
});
40+
41+
it('should reply 404 if route doesnt exist', async function () {
42+
let output = await fetch("http://localhost:5000/routeNotExist?name=world", { method: 'GET'});
43+
output = await output.json();
44+
expect(output).eql({
45+
"statusCode": 404,
46+
"error": "Not Found",
47+
"message": "Not Found"
48+
});
49+
});
4050
});

0 commit comments

Comments
 (0)