Search code examples
next.jsnext-auth

How can I protect multiple Next.js API routes in next-auth


I build a simple API in Next.js and I use next-auth for authentication.

So far I have to use something like this in every API route:

  const session = await getSession({ req });
  if (session) {
    ... do something ...
  } else {
    ... send back a 401 status
  }

This seems to go against the DRY principle. Is there a clever way to apply protection to a number of routes in one place, such as Laravel route groups?


Solution

  • Create a middleware that gets the session otherwise returns 401.

    See NextJS docs on api middleware.
    You can also check out their example in the github repo.