Published on

How to implement Bearer Authentication in Next.js API

Authors

Bearer Authentication is an HTTP-based authentication method in which the client side needs to send a token in request headers.

Usually, it will be in the following format.

Authorization: Bearer <token>

And in the backend, we parse the token and compare it to our expected token for authentication.

Let's see how to implement that in Next.js

// https://nextjs.org/docs/api-routes/introduction
export default function handler(req, res) {
  const authToken = (req.headers.authorization || '').split("Bearer ").at(1)
  // replace ADMIN_AUTH_TOKEN with your expected token
  if (authToken && authToken === process.env.ADMIN_AUTH_TOKEN) { 
    res.status(200).json({ hello: 'world' })
  }
  res.status(401).json({ error: "Invalid Auth Token" });
}

Happy doing Bearer-auth!

References