Next.js Security

Auth Middleware

JWT verification, role-based access, session refresh, and protected APIs.

Advertisement

Auth Middleware

JWT verification, role-based access, session refresh, and protected APIs.

Overview

Middleware provides the first line of defense for authentication.

Key Concepts

  • JWT Verification — Validate tokens in middleware
  • Role-Based Access — Control access by user role
  • Session Refresh — Refresh expired tokens
  • Protected APIs — Secure API routes
  • CORS — Handle cross-origin requests

Code Examples

// middleware.js
import { NextResponse } from 'next/server';
import { verifyToken } from './lib/auth';

export async function middleware(request) {
  const token = request.cookies.get('token')?.value;

  // Public routes
  const publicPaths = ['/login', '/register', '/api/auth'];
  if (publicPaths.some(path => request.nextUrl.pathname.startsWith(path))) {
    return NextResponse.next();
  }

  // Check authentication
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  try {
    const payload = await verifyToken(token);
    
    // Role-based access
    if (request.nextUrl.pathname.startsWith('/admin') && payload.role !== 'admin') {
      return NextResponse.redirect(new URL('/unauthorized', request.url));
    }

    // Add user to headers
    const response = NextResponse.next();
    response.headers.set('x-user-id', payload.sub);
    response.headers.set('x-user-role', payload.role);
    
    return response;
  } catch (error) {
    // Token expired - try refresh
    const refreshToken = request.cookies.get('refreshToken')?.value;
    if (refreshToken) {
      try {
        const newTokens = await refreshTokens(refreshToken);
        const response = NextResponse.next();
        response.cookies.set('token', newTokens.accessToken, { httpOnly: true });
        response.cookies.set('refreshToken', newTokens.refreshToken, { httpOnly: true });
        return response;
      } catch {
        return NextResponse.redirect(new URL('/login', request.url));
      }
    }
    
    return NextResponse.redirect(new URL('/login', request.url));
  }
}

Practice

Implement JWT-based middleware with role-based access control and token refresh.