Robert Hufsky
Robert Hufsky

Reputation: 199

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?

Upvotes: 2

Views: 6370

Answers (2)

Make a middleware!

Disregard the typing if your not using TS

import { NextApiRequest, NextApiResponse } from 'next/types'
import { getSession } from 'next-auth/client'

export const protect = async (
  req: NextApiRequest,
  res: NextApiResponse,
  next: any
) => {
  const session = await getSession({ req })
  if (session) {
    console.log(session)
    next()
  } else {
    res.status(401)
    throw new Error('Not authorized')
  }
}

Upvotes: 3

Mellet
Mellet

Reputation: 1306

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.

Upvotes: 1

Related Questions