0
0
NextjsHow-ToBeginner · 4 min read

How to Protect API Route in Next.js: Simple Authentication Guide

To protect an API route in Next.js, check the user's authentication status inside the API handler or middleware before processing the request. Use tokens or session cookies to verify identity and return 401 Unauthorized if the user is not authenticated.
📐

Syntax

Protecting an API route involves checking authentication inside the API handler function. You typically:

  • Import authentication helpers or middleware.
  • Check the request headers or cookies for a valid token or session.
  • Return a 401 Unauthorized response if the check fails.
  • Proceed with the API logic if the user is authenticated.
javascript
export default async function handler(req, res) {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token || !isValidToken(token)) {
    return res.status(401).json({ message: 'Unauthorized' });
  }
  // Continue with protected logic
  res.status(200).json({ data: 'Protected data' });
}

function isValidToken(token) {
  // Your token validation logic here
  return token === 'valid-token';
}
💻

Example

This example shows a Next.js API route that protects data by checking a simple token in the Authorization header. If the token is missing or invalid, it returns 401 Unauthorized. Otherwise, it returns protected data.

javascript
export default function handler(req, res) {
  const authHeader = req.headers.authorization;
  if (!authHeader) {
    return res.status(401).json({ message: 'Unauthorized: No token provided' });
  }

  const token = authHeader.split(' ')[1];
  if (token !== 'secret-token') {
    return res.status(401).json({ message: 'Unauthorized: Invalid token' });
  }

  res.status(200).json({ message: 'Access granted to protected API route' });
}
Output
If called without or with wrong token: {"message":"Unauthorized: No token provided"} or {"message":"Unauthorized: Invalid token"} If called with header Authorization: Bearer secret-token Response: {"message":"Access granted to protected API route"}
⚠️

Common Pitfalls

Common mistakes when protecting API routes include:

  • Not checking authentication at all, leaving routes open.
  • Checking authentication only on the client side, which can be bypassed.
  • Forgetting to return after sending a 401 response, causing code to continue running.
  • Hardcoding tokens insecurely instead of using environment variables.
javascript
export default function handler(req, res) {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token || token !== process.env.SECRET_TOKEN) {
    res.status(401).json({ message: 'Unauthorized' });
    // Missing return here causes code to continue
    return;
  }
  // This runs even if unauthorized
  res.status(200).json({ message: 'Protected data' });
}

// Correct way:
export default function handler(req, res) {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token || token !== process.env.SECRET_TOKEN) {
    return res.status(401).json({ message: 'Unauthorized' });
  }
  res.status(200).json({ message: 'Protected data' });
}
📊

Quick Reference

Tips to protect API routes in Next.js:

  • Always check authentication inside the API route handler or middleware.
  • Use return after sending unauthorized responses to stop execution.
  • Store secrets like tokens in environment variables, not in code.
  • Consider using libraries like next-auth or JWT for robust authentication.
  • Test your protected routes with and without valid credentials.

Key Takeaways

Always verify user authentication inside your Next.js API route before processing requests.
Return a 401 status and stop execution immediately if authentication fails.
Use environment variables to store secret tokens or keys securely.
Client-side checks alone are not enough; protect routes on the server side.
Consider using authentication libraries for easier and safer implementation.