NextJsAPI Authentication

You can handle authentication using JSON Web Tokens (JWT) or OAuth inside Next.js API routes. Protect pages and endpoints based on user sessions.

pages/api/login.js
export default function handler(req, res) {
  if (req.method === 'POST') {
    const { username, password } = req.body;
    if (username === 'admin' && password === 'secret') {
      return res.status(200).json({ token: 'fake-jwt-token' });
    }
    return res.status(401).json({ error: 'Invalid credentials' });
  }
  res.status(405).json({ error: 'Method not allowed' });
}