I am using next-auth to authenticate users. When I navigate to api routes that don't exist on my NextJS server, I get a 404 response and an error page. I would like to emulate this behaviour when an unauthenticated user navigates to one of my api routes. My current test route looks something like this:
// api/test.js
import { getSession } from 'next-auth/client'
export default async (req, res) => {
const session = await getSession({ req });
if (session) {
// Signed in
res.json(JSON.stringify(session, null, 2));
} else {
// Not Signed in
res.status(404);
}
res.end();
}
Unfortunately, this results in a blank page. Ideally, I would like if an unauthenticated user could not tell the difference between a page that doesn't exist and a blocked api route. I also noticed that when I curl a non-existing route, e.g. curl -i http://localhost:3000/api
, I get the following response (as well as all of the html for the error page):
HTTP/1.1 404 Not Found
Cache-Control: no-store, must-revalidate
X-Powered-By: Next.js
Content-Type: text/html; charset=utf-8
Content-Length: 2427
Vary: Accept-Encoding
Date: Thu, 20 May 2021 10:45:45 GMT
Connection: keep-alive
Keep-Alive: timeout=5
When I run curl -i http://localhost:3000/api/test
to hit the above code I get the following response:
HTTP/1.1 404 Not Found
Date: Thu, 20 May 2021 10:44:57 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Transfer-Encoding: chunked
How do I modify the response when the user is not authenticated to look (and return the same headers) as the default NextJS 404 error response?