Advertisement
Intermediate Next.js, API Routes

How can you protect an API route so that only authenticated users can access it?

Short answer

You check for a valid session or authentication token at the start of your handler, usually by reading a cookie or an authorization header, and return a 401 unauthorized response immediately if the check fails, before running any of the protected logic.

Save Next.js mock interview
Advertisement
AModel answer
You check for a valid session or authentication token at the start of your handler, usually by reading a cookie or an authorization header, and return a 401 unauthorized response immediately if the check fails, before running any of the protected logic.
export default function handler(req, res) {
  const token = req.cookies.session;
  if (!token) {
    return res.status(401).json({ error: 'Not authenticated' });
  }
  res.status(200).json({ secret: 'protected data' });
}
Real-world example
An account settings API route checks for a valid session cookie before allowing a user to update their profile information, blocking anyone who is not properly signed in.
Likely follow-ups
  • Should authentication checks be duplicated in every route or centralized somewhere?
  • How does this compare to using middleware for authentication?
Related topics