0

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?

Julien
  • 45
  • 7
  • 2
    The HTTP code should probably be 401 (unauthorized) not 404 (not found) https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_client_errors – evolutionxbox May 20 '21 at 11:22
  • 1
    True, 401 would probably be more accurate, however I want to hide the presence of this route to unauthenticated users. In general, perhaps the best solution would be to return 401 to all api routes, and then 404 if the user is not authorised, as suggested in [this answer](https://stackoverflow.com/a/4039015/9194806) – Julien May 20 '21 at 11:41

0 Answers0