Next.js course ยท Module 7: Authentication and Authorization

Middleware for route protection

19 min read ยท
In this lesson6

In previous modules, we learned the basics of authentication, connecting external providers, session management, and implementation of the role and permission system. Now we will focus on middleware - a powerful Next.js mechanism that allows executing code before reaching the target request, which is an ideal place to implement route protection.

Middleware in Next.js works at the server level but is executed before page rendering or API request handling. This enables centralized access management, redirecting, header modification, and many other operations.

Middleware basics in Next.js

Let's start by understanding how middleware works in Next.js:

  1. Location - middleware is defined in the middleware.ts file (or middleware.js) in the main directory of the Next.js project. Since Next.js 16 this file is called proxy.ts (with a proxy function), the middleware name is deprecated, and proxy runs on the Node.js runtime.
  2. Execution - middleware runs before page rendering or API request handling.
  3. Matching - you can specify for which paths the middleware should be executed.
  4. Action - middleware can redirect the user, modify the request/response, or simply proceed to the next step in the processing chain.

Simple middleware example:

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  console.log('Middleware executed for:', request.nextUrl.pathname);

  // Continue normal request processing
  return NextResponse.next();
}

// Apply middleware only to specific paths
export const config = {
  matcher: ['/dashboard/:path*', '/api/:path*'],
};

Implementing middleware for route protection

Now let's move on to the full implementation of middleware for route protection in a Next.js application.

1. Basic authentication middleware

Let's start with simple middleware that checks if the user is logged in and protects specific paths:

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';

export async function middleware(request: NextRequest) {
  // Get the session token from the cookie
  const token = await getToken({ req: request });

  // Check if user is logged in
  const isLoggedIn = !!token;

  // Current path
  const { pathname } = request.nextUrl;

  // Protected paths - requiring login
  const protectedPaths = [
    '/dashboard',
    '/profile',
    '/settings',
  ];

  // Paths only for unauthenticated users (e.g. login page)
  const authPaths = ['/auth/login', '/auth/register'];

  // Check if the current path is protected
  const isProtectedPath = protectedPaths.some(path =>
    pathname === path || pathname.startsWith(`${path}/`)
  );

  // Check if the current path is an authentication page
  const isAuthPath = authPaths.some(path => pathname === path);

  // If the user tries to access a protected path but is not logged in
  if (isProtectedPath && !isLoggedIn) {
    // Redirect to the login page with information about the target path
    const url = new URL('/auth/login', request.url);
    url.searchParams.set('callbackUrl', encodeURI(pathname));
    return NextResponse.redirect(url);
  }

  // If the user is logged in and tries to access the login/registration page
  if (isAuthPath && isLoggedIn) {
    // Redirect to the dashboard
    return NextResponse.redirect(new URL('/dashboard', request.url));
  }

  // In other cases, continue normal processing
  return NextResponse.next();
}

// Specify for which paths the middleware should run
export const config = {
  matcher: [
    /*
     * Match all paths except:
     * 1. Static files (e.g. /favicon.ico, /images/*, etc.)
     * 2. next-auth API Route (/api/auth/*, which handles authentication itself)
     */
    '/((?!api/auth|_next/static|_next/image|favicon.ico).*)',
  ],
};

2. Advanced middleware with role and permission control

Let's extend our middleware to also include user roles and permissions:

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';

// Structure describing access requirements for paths
interface PathConfig {
  requireAuth: boolean;        // Whether login is required
  roles?: string[];            // Allowed roles (if empty, all roles have access)
  permissions?: string[];      // Required permissions
}

// Path access configuration
const pathAccessConfig: Record<string, PathConfig> = {
  // Administrative paths
  '/admin': {
    requireAuth: true,
    roles: ['admin'],
  },

  // Moderator paths
  '/moderator': {
    requireAuth: true,
    roles: ['admin', 'moderator'],
  },

  // Dashboard paths - require login
  '/dashboard': {
    requireAuth: true,
  },

  // User management page - requires user:manage permission
  '/admin/users': {
    requireAuth: true,
    roles: ['admin'],
    permissions: ['user:manage'],
  },

  // Public paths - available to everyone
  '/': {
    requireAuth: false,
  },
  '/about': {
    requireAuth: false,
  },
  '/contact': {
    requireAuth: false,
  },

  // Authentication paths - available only to unauthenticated
  '/auth/login': {
    requireAuth: false,
  },
  '/auth/register': {
    requireAuth: false,
  },
};

// Helper function to check whether a path matches a configuration
function matchPathConfig(pathname: string): [string, PathConfig] | null {
  // Check exact match
  if (pathAccessConfig[pathname]) {
    return [pathname, pathAccessConfig[pathname]];
  }

  // Check prefix match
  for (const configPath in pathAccessConfig) {
    // Ignore exact matches since we already checked them
    if (configPath === pathname) continue;

    // Check if the current path starts with the configured path + /
    if (pathname.startsWith(`${configPath}/`)) {
      return [configPath, pathAccessConfig[configPath]];
    }
  }

  // No match
  return null;
}

export async function middleware(request: NextRequest) {
  // Get the session token from the cookie
  const token = await getToken({ req: request });

  // Current path
  const { pathname } = request.nextUrl;

  // Find access configuration for the current path
  const pathMatch = matchPathConfig(pathname);

  // If no configuration was found for this path, continue normal processing
  if (!pathMatch) {
    return NextResponse.next();
  }

  const [configPath, config] = pathMatch;

  // Authentication pages - redirect to dashboard if the user is already logged in
  if (
    !config.requireAuth &&
    (pathname === '/auth/login' || pathname === '/auth/register') &&
    token
  ) {
    return NextResponse.redirect(new URL('/dashboard', request.url));
  }

  // If the path requires authentication and the user is not logged in
  if (config.requireAuth && !token) {
    // Redirect to the login page with information about the target path
    const url = new URL('/auth/login', request.url);
    url.searchParams.set('callbackUrl', pathname);
    return NextResponse.redirect(url);
  }

  // If the path requires specific roles, check the user's permissions
  if (token && config.roles && config.roles.length > 0) {
    const userRoles = token.role as string;

    if (!config.roles.includes(userRoles)) {
      // User does not have the required role - redirect to the no-permissions page
      return NextResponse.redirect(new URL('/auth/unauthorized', request.url));
    }
  }

  // If the path requires specific permissions, check the user's permissions
  if (token && config.permissions && config.permissions.length > 0) {
    const userPermissions = token.permissions as string[] || [];

    // Check if the user has all required permissions
    const hasAllPermissions = config.permissions.every(permission =>
      userPermissions.includes(permission)
    );

    if (!hasAllPermissions) {
      // User does not have the required permissions - redirect to the no-permissions page
      return NextResponse.redirect(new URL('/auth/unauthorized', request.url));
    }
  }

  // All conditions met - continue
  return NextResponse.next();
}

// Match for all paths except static files and authentication API
export const config = {
  matcher: [
    '/((?!api/auth|_next/static|_next/image|images|favicon.ico).*)',
  ],
};

3. Middleware for the authentication API

As you can see, the described middleware works for pages, redirecting the user in case of missing permissions. For API routes, we should return appropriate error codes rather than redirecting the user. Here is the middleware implementation specifically for API:

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';

// API path access configuration
const apiAccessConfig: Record<string, {
  roles?: string[];
  permissions?: string[];
}> = {
  // Administrator API
  '/api/admin': {
    roles: ['admin'],
  },

  // Moderator API
  '/api/moderator': {
    roles: ['admin', 'moderator'],
  },

  // User management API
  '/api/users': {
    permissions: ['user:read'],
  },
  '/api/users/create': {
    permissions: ['user:create'],
  },
  '/api/users/update': {
    permissions: ['user:update'],
  },
  '/api/users/delete': {
    permissions: ['user:delete'],
  },
};

// Helper function to check whether an API path matches a configuration
function matchApiConfig(pathname: string) {
  // Check exact match
  if (apiAccessConfig[pathname]) {
    return [pathname, apiAccessConfig[pathname]];
  }

  // Check prefix match
  for (const configPath in apiAccessConfig) {
    if (pathname.startsWith(`${configPath}/`)) {
      return [configPath, apiAccessConfig[configPath]];
    }
  }

  return null;
}

export async function middleware(request: NextRequest) {
  // Get the session token
  const token = await getToken({ req: request });

  // Current path
  const { pathname } = request.nextUrl;

  // Check if this is an API request
  const isApiRequest = pathname.startsWith('/api/');

  // If it is not API, proceed to the next middleware
  if (!isApiRequest) {
    return NextResponse.next();
  }

  // Skip authentication routes
  if (pathname.startsWith('/api/auth/')) {
    return NextResponse.next();
  }

  // If it is API and the user is not logged in
  if (!token) {
    return NextResponse.json(
      { error: 'Unauthorized - Authentication required' },
      { status: 401 }
    );
  }

  // Find access configuration for this API endpoint
  const apiMatch = matchApiConfig(pathname);

  // If no configuration, we assume being logged in is sufficient
  if (!apiMatch) {
    return NextResponse.next();
  }

  const [configPath, config] = apiMatch;

  // Check user role
  if (config.roles && config.roles.length > 0) {
    const userRoles = token.role as string;

    if (!config.roles.includes(userRoles)) {
      return NextResponse.json(
        { error: 'Forbidden - Insufficient role permissions' },
        { status: 403 }
      );
    }
  }

  // Check user permissions
  if (config.permissions && config.permissions.length > 0) {
    const userPermissions = token.permissions as string[] || [];

    const hasAllPermissions = config.permissions.every(permission =>
      userPermissions.includes(permission)
    );

    if (!hasAllPermissions) {
      return NextResponse.json(
        { error: 'Forbidden - Insufficient permissions' },
        { status: 403 }
      );
    }
  }

  // All conditions met
  return NextResponse.next();
}

// Match for all API routes
export const config = {
  matcher: ['/api/:path*'],
};

4. Combining middleware for pages and API

We can combine both approaches in a single middleware:

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';

// Page access configuration
const pageAccessConfig: Record<string, {
  requireAuth: boolean;
  roles?: string[];
  permissions?: string[];
}> = {
  '/admin': { requireAuth: true, roles: ['admin'] },
  '/moderator': { requireAuth: true, roles: ['admin', 'moderator'] },
  '/dashboard': { requireAuth: true },
  '/profile': { requireAuth: true },
  '/settings': { requireAuth: true },
  '/': { requireAuth: false },
  '/about': { requireAuth: false },
  '/auth/login': { requireAuth: false },
  '/auth/register': { requireAuth: false },
};

// API access configuration
const apiAccessConfig: Record<string, {
  roles?: string[];
  permissions?: string[];
}> = {
  '/api/admin': { roles: ['admin'] },
  '/api/moderator': { roles: ['admin', 'moderator'] },
  '/api/users': { permissions: ['user:read'] },
  '/api/users/create': { permissions: ['user:create'] },
};

// Helper functions for path matching (omitted for brevity)
//
export async function middleware(request: NextRequest) {
  // Get the session token
  const token = await getToken({ req: request });
  const { pathname } = request.nextUrl;

  // Check if this is an API request
  const isApiRequest = pathname.startsWith('/api/');

  // Skip authentication routes
  if (pathname.startsWith('/api/auth/')) {
    return NextResponse.next();
  }

  // API request handling
  if (isApiRequest) {
    // If it is API and the user is not logged in (for protected endpoints)
    if (!token && !pathname.startsWith('/api/public/')) {
      return NextResponse.json(
        { error: 'Unauthorized - Authentication required' },
        { status: 401 }
      );
    }

    // Match API configuration
    const apiMatch = matchApiConfig(pathname);
    if (apiMatch && token) {
      const [configPath, config] = apiMatch;

      // Check role and permissions
      if (!hasRequiredRoles(token, config.roles) ||
          !hasRequiredPermissions(token, config.permissions)) {
        return NextResponse.json(
          { error: 'Forbidden - Insufficient permissions' },
          { status: 403 }
        );
      }
    }
  }
  // Page handling
  else {
    // Match page configuration
    const pageMatch = matchPageConfig(pathname);
    if (pageMatch) {
      const [configPath, config] = pageMatch;

      // Authentication pages - redirect if the user is logged in
      if (
        !config.requireAuth &&
        (pathname === '/auth/login' || pathname === '/auth/register') &&
        token
      ) {
        return NextResponse.redirect(new URL('/dashboard', request.url));
      }

      // If the page requires authentication and the user is not logged in
      if (config.requireAuth && !token) {
        const url = new URL('/auth/login', request.url);
        url.searchParams.set('callbackUrl', pathname);
        return NextResponse.redirect(url);
      }

      // If the user is logged in, check role and permissions
      if (token && config.requireAuth) {
        if (!hasRequiredRoles(token, config.roles) ||
            !hasRequiredPermissions(token, config.permissions)) {
          return NextResponse.redirect(new URL('/auth/unauthorized', request.url));
        }
      }
    }
  }

  // All conditions met
  return NextResponse.next();
}

// Helper functions for checking roles and permissions
function hasRequiredRoles(token: any, requiredRoless?: string[]): boolean {
  if (!requiredRoless || requiredRoless.length === 0) return true;

  const userRoles = token.role as string;
  return requiredRoless.includes(userRoles);
}

function hasRequiredPermissions(token: any, requiredPermissions?: string[]): boolean {
  if (!requiredPermissions || requiredPermissions.length === 0) return true;

  const userPermissions = token.permissions as string[] || [];
  return requiredPermissions.every(permission => userPermissions.includes(permission));
}

// Functions matching path configuration (implementation omitted for brevity)
function matchPageConfig(pathname: string) { /* ... */ }
function matchApiConfig(pathname: string) { /* ... */ }

export const config = {
  matcher: [
    '/((?!_next/static|_next/image|images|favicon.ico).*)',
  ],
};

Middleware for handling specific access patterns

Often we need middleware that handles specific use cases. Let's look at some examples:

1. Middleware for request rate limiting (Rate Limiting)

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

// Simple in-memory request limit implementation
// In production, you should use Redis or a similar solution
const REQUESTS_PER_MINUTE = 60;
const WINDOW_SIZE_MS = 60 * 1000; // 1 minute

interface RateLimitState {
  requests: number;
  timestamp: number;
}

const ipRequestCounts = new Map<string, RateLimitState>();

export function middleware(request: NextRequest) {
  // Get the user's IP address
  const ip = request.ip || 'unknown';

  // Check if it is API
  if (!request.nextUrl.pathname.startsWith('/api/')) {
    return NextResponse.next();
  }

  // Get the current limit state for this IP
  const now = Date.now();
  const state = ipRequestCounts.get(ip) || { requests: 0, timestamp: now };

  // If the time window has passed, reset the counter
  if (now - state.timestamp > WINDOW_SIZE_MS) {
    state.requests = 0;
    state.timestamp = now;
  }

  // Increment the request counter
  state.requests++;
  ipRequestCounts.set(ip, state);

  // If the limit is exceeded, return error 429 (Too Many Requests)
  if (state.requests > REQUESTS_PER_MINUTE) {
    const response = NextResponse.json(
      { error: 'Rate limit exceeded. Please try again later.' },
      { status: 429 }
    );

    // Set headers informing about limits
    response.headers.set('X-RateLimit-Limit', REQUESTS_PER_MINUTE.toString());
    response.headers.set('X-RateLimit-Remaining', '0');
    response.headers.set('Retry-After',
      Math.ceil((state.timestamp + WINDOW_SIZE_MS - now) / 1000).toString()
    );

    return response;
  }

  // Within the limit - continue
  const response = NextResponse.next();

  // Set headers informing about limits
  response.headers.set('X-RateLimit-Limit', REQUESTS_PER_MINUTE.toString());
  response.headers.set(
    'X-RateLimit-Remaining',
    Math.max(0, REQUESTS_PER_MINUTE - state.requests).toString()
  );

  return response;
}

export const config = {
  matcher: ['/api/:path*'],
};

2. Middleware for geolocation (Country-based access)

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

// List of allowed country codes
const ALLOWED_COUNTRIES = ['US', 'CA', 'GB', 'DE', 'FR', 'PL'];

// List of pages subject to geographic restrictions
const GEO_RESTRICTED_PATHS = [
  '/premium-content',
  '/members-only',
];

export function middleware(request: NextRequest) {
  // Check if the path is subject to geographic restrictions
  const isGeoRestrictedPath = GEO_RESTRICTED_PATHS.some(path =>
    request.nextUrl.pathname === path ||
    request.nextUrl.pathname.startsWith(`${path}/`)
  );

  if (isGeoRestrictedPath) {
    // Get the user's country information from headers (available on the Vercel platform)
    const country = request.geo?.country || 'Unknown';

    // If the user's country is not on the allowed list
    if (!ALLOWED_COUNTRIES.includes(country)) {
      return NextResponse.redirect(new URL('/geo-restricted', request.url));
    }
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    '/premium-content/:path*',
    '/members-only/:path*',
  ],
};

3. Middleware for modifying security headers

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  // Get the original response
  const response = NextResponse.next();

  // Add security headers

  // Protect against XSS attacks
  response.headers.set('X-XSS-Protection', '1; mode=block');

  // Prevent MIME type "sniffing"
  response.headers.set('X-Content-Type-Options', 'nosniff');

  // Control how the page can be embedded in an iframe
  response.headers.set('X-Frame-Options', 'SAMEORIGIN');

  // Content Security Policy - more advanced protection against XSS
  response.headers.set(
    'Content-Security-Policy',
    "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https:; connect-src 'self' https://api.example.com;"
  );

  // HTTP Strict Transport Security - forces HTTPS use
  response.headers.set(
    'Strict-Transport-Security',
    'max-age=31536000; includeSubDomains; preload'
  );

  // Permissions Policy - declare which browser features are allowed
  response.headers.set(
    'Permissions-Policy',
    'camera=(), microphone=(), geolocation=(self), interest-cohort=()'
  );

  return response;
}

export const config = {
  matcher: [
    '/((?!_next/static|_next/image|images|favicon.ico).*)',
  ],
};

4. Middleware for A/B testing

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

// A/B experiment configuration
const AB_TESTS = {
  'new-landing-page': {
    variants: ['control', 'variant-a', 'variant-b'],
    weights: [0.34, 0.33, 0.33], // Traffic split
    paths: ['/'],  // Paths covered by the test
    cookieName: 'ab-new-landing',
  },
  'checkout-flow': {
    variants: ['original', 'simplified'],
    weights: [0.5, 0.5],
    paths: ['/checkout', '/cart'],
    cookieName: 'ab-checkout',
  },
};

export function middleware(request: NextRequest) {
  const url = request.nextUrl;
  const response = NextResponse.next();

  // Iterate through the defined tests
  for (const [testName, test] of Object.entries(AB_TESTS)) {
    // Check if the current path is covered by the test
    const isTestPath = test.paths.some(path =>
      url.pathname === path || url.pathname.startsWith(`${path}/`)
    );

    if (isTestPath) {
      // Check if the user already has a test variant assigned
      const existingVariant = request.cookies.get(test.cookieName)?.value;
      let variant = existingVariant;

      // If the user has no assigned variant, assign a new one
      if (!variant) {
        variant = assignVariant(test.variants, test.weights);

        // Set a cookie with the assigned variant
        response.cookies.set(test.cookieName, variant, {
          maxAge: 60 * 60 * 24 * 30, // 30 days
          path: '/',
        });
      }

      // Add a header with test variant information
      response.headers.set(`X-AB-Test-${testName}`, variant);

      // You can also set a rewrite to a different page for different variants
      if (testName === 'new-landing-page' && url.pathname === '/') {
        if (variant === 'variant-a') {
          // Internal redirect (invisible to the user)
          return NextResponse.rewrite(new URL('/landing-a', request.url));
        } else if (variant === 'variant-b') {
          return NextResponse.rewrite(new URL('/landing-b', request.url));
        }
      }
    }
  }

  return response;
}

// Function that assigns a variant based on weights
function assignVariant(variants: string[], weights: number[]): string {
  const randomNum = Math.random();
  let cumulativeWeight = 0;

  for (let i = 0; i < variants.length; i++) {
    cumulativeWeight += weights[i];
    if (randomNum < cumulativeWeight) {
      return variants[i];
    }
  }

  // Fall back to the first variant
  return variants[0];
}

export const config = {
  matcher: [
    '/', '/checkout', '/cart',
    '/landing-a', '/landing-b',
  ],
};

Testing middleware

Tests are very important to verify that middleware works correctly, especially since it handles key application security aspects. Here is a simple example of unit tests:

// __tests__/middleware.test.ts
import { NextRequest } from 'next/server';
import { middleware } from '../middleware';
import { getToken } from 'next-auth/jwt';

// We mock getToken from next-auth/jwt
jest.mock('next-auth/jwt', () => ({
  getToken: jest.fn(),
}));

describe('Auth Middleware', () => {
  // Setup and reset before each test
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('should redirect unauthenticated user from protected route to login page', async () => {
    // Mock getToken returning null (unauthenticated user)
    (getToken as jest.Mock).mockResolvedValueOnce(null);

    // Create a test request to a protected path
    const req = new NextRequest(new URL('http://localhost:3000/dashboard'));

    // Run the middleware
    const response = await middleware(req);

    // Check that it redirects to the login page
    expect(response).not.toBeNull();
    expect(response.status).toBe(307); // Redirect status code
    expect(response.headers.get('location')).toBe('http://localhost:3000/auth/login?callbackUrl=%2Fdashboard');
  });

  it('should allow authenticated user to access protected route', async () => {
    // Mock getToken returning a token (logged-in user)
    (getToken as jest.Mock).mockResolvedValueOnce({
      name: 'Test User',
      email: 'test@example.com',
      role: 'user',
      permissions: ['content:read']
    });

    // Create a test request to a protected path
    const req = new NextRequest(new URL('http://localhost:3000/dashboard'));

    // Run the middleware
    const response = await middleware(req);

    // Check that it allows access
    expect(response).not.toBeNull();
    expect(response.status).toBe(200);
  });

  it('should redirect authenticated user from login page to dashboard', async () => {
    // Mock getToken returning a token (logged-in user)
    (getToken as jest.Mock).mockResolvedValueOnce({
      name: 'Test User',
      email: 'test@example.com',
    });

    // Create a test request to the login page
    const req = new NextRequest(new URL('http://localhost:3000/auth/login'));

    // Run the middleware
    const response = await middleware(req);

    // Check that it redirects to the dashboard
    expect(response).not.toBeNull();
    expect(response.status).toBe(307);
    expect(response.headers.get('location')).toBe('http://localhost:3000/dashboard');
  });

  it('should redirect user without admin role from admin page', async () => {
    // Mock getToken returning a token with user role
    (getToken as jest.Mock).mockResolvedValueOnce({
      name: 'Test User',
      email: 'test@example.com',
      role: 'user',
      permissions: ['content:read']
    });

    // Create a test request to the admin page
    const req = new NextRequest(new URL('http://localhost:3000/admin/dashboard'));

    // Run the middleware
    const response = await middleware(req);

    // Check that it redirects to the no-permissions page
    expect(response).not.toBeNull();
    expect(response.status).toBe(307);
    expect(response.headers.get('location')).toBe('http://localhost:3000/auth/unauthorized');
  });
});

Best practices and patterns

1. Performance optimization middleware

Middleware is executed on every request, so it's important that it's as efficient as possible:

  • Limit external API calls - Middleware should be fast. Avoid API calls in middleware when possible.
  • Use caching - If you must fetch data, consider caching it.
  • Define matcher precisely - Limit middleware execution only to paths that need it.

2. Debugging middleware

Debugging middleware can be difficult because it runs "behind the scenes":

  • Add logs - Use console.log() to trace middleware activity.
  • Add debug headers - You can add custom response headers to track what is happening.
// Example of adding debug headers
const response = NextResponse.next();
response.headers.set('X-Debug-Path', request.nextUrl.pathname);
response.headers.set('X-Debug-Auth', token ? 'Authenticated' : 'Unauthenticated');
return response;

3. Organizing middleware code

For complex applications, it's worth considering middleware modularization:

// middleware/auth.ts
import { NextRequest, NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';

export async function authMiddleware(req: NextRequest) {
  // Authentication middleware implementation
  //
}

// middleware/security.ts
import { NextRequest, NextResponse } from 'next/server';

export function securityHeadersMiddleware(req: NextRequest) {
  // Security headers middleware implementation
  //
}

// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { authMiddleware } from './middleware/auth';
import { securityHeadersMiddleware } from './middleware/security';

export async function middleware(req: NextRequest) {
  // Check if the path requires authentication
  if (req.nextUrl.pathname.startsWith('/dashboard') ||
      req.nextUrl.pathname.startsWith('/admin')) {
    return await authMiddleware(req);
  }

  // Add security headers to all responses
  return securityHeadersMiddleware(req);
}

export const config = { /* ... */ };

Summary

Middleware in Next.js offers a powerful mechanism for implementing route protection and many other server-level features. In this module we learned:

  1. Middleware basics in Next.js - how it works and how to configure it
  2. Authentication middleware implementation - how to protect routes from unauthorized access
  3. Middleware with role and permission control - how to provide access based on user roles
  4. Specialized middleware - how to implement rate limiting, geolocation, security headers, and A/B tests
  5. Middleware testing - how to write tests for middleware
  6. Best practices and patterns - how to optimize and organize middleware code

A good middleware implementation is a key element of Next.js application security and performance. Thanks to the techniques presented in this module, you can create advanced, multi-layered protections for your applications.

In the next module, we will move on to implementing a Context Provider for authentication, which will enable easy access to authentication data throughout the application.

Code for this lesson: App.tsx
import React, { useState } from 'react';

// Demo: Middleware for route protection in Next.js
interface Route {
  path: string;
  label: string;
  isProtected: boolean;
  requiredRole?: string;
  icon: string;
}

const routes: Route[] = [
  { path: '/', label: 'Home page', isProtected: false, icon: 'H' },
  { path: '/about', label: 'About us', isProtected: false, icon: 'A' },
  { path: '/dashboard', label: 'Dashboard', isProtected: true, requiredRole: 'user', icon: 'D' },
  { path: '/admin', label: 'Admin Panel', isProtected: true, requiredRole: 'admin', icon: 'S' },
  { path: '/admin/users', label: 'Users', isProtected: true, requiredRole: 'admin', icon: 'U' },
  { path: '/api/data', label: 'API: Data', isProtected: true, requiredRole: 'user', icon: 'P' },
  { path: '/login', label: 'Login', isProtected: false, icon: 'L' },
  { path: '/profile', label: 'Profile', isProtected: true, requiredRole: 'user', icon: 'R' },
];

function MiddlewareDemo() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [userRole, setUserRole] = useState<'user' | 'admin'>('user');
  const [requestLog, setRequestLog] = useState<{ path: string; result: string; color: string }[]>([]);

  const simulateRequest = (route: Route) => {
    let result = '';
    let color = '';

    if (!route.isProtected) {
      result = '200 OK - Public page';
      color = '#10b981';
    } else if (!isLoggedIn) {
      result = '302 Redirect -> /login (no token)';
      color = '#f59e0b';
    } else if (route.requiredRole === 'admin' && userRole !== 'admin') {
      result = '403 Forbidden - required role: admin';
      color = '#ef4444';
    } else {
      result = '200 OK - Access granted (' + userRole + ')';
      color = '#10b981';
    }

    setRequestLog(prev => [{ path: route.path, result, color }, ...prev.slice(0, 9)]);
  };

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#e0e0e0', fontFamily: 'system-ui' }}>
      <h1 style={{ color: '#64ffda', marginBottom: '8px' }}>Middleware - Route Protection</h1>
      <p style={{ color: '#8892b0', marginBottom: '24px' }}>Simulation of Next.js middleware for route protection</p>

      <div style={{ display: 'flex', gap: '16px', marginBottom: '24px', alignItems: 'center', flexWrap: 'wrap' }}>
        <label style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer' }}>
          <input type="checkbox" checked={isLoggedIn} onChange={e => setIsLoggedIn(e.target.checked)} />
          <span>Logged in</span>
        </label>
        {isLoggedIn && (
          <select value={userRole} onChange={e => setUserRole(e.target.value as 'user' | 'admin')} style={{ padding: '6px 12px', borderRadius: '6px', background: '#1a1a2e', color: '#fff', border: '1px solid #333' }}>
            <option value="user">user</option>
            <option value="admin">admin</option>
          </select>
        )}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
        <div>
          <h3 style={{ color: '#64ffda', fontSize: '16px' }}>Routes</h3>
          {routes.map(route => (
            <button key={route.path} onClick={() => simulateRequest(route)} style={{
              display: 'block', width: '100%', padding: '12px', marginBottom: '8px', borderRadius: '8px', border: '1px solid #333',
              background: '#1a1a2e', color: '#e0e0e0', cursor: 'pointer', textAlign: 'left',
            }}>
              <code style={{ color: '#64ffda' }}>{route.path}</code>
              <div style={{ fontSize: '12px', color: '#8892b0' }}>
                {route.isProtected ? 'Protected (role: ' + route.requiredRole + ')' : 'Public'}
              </div>
            </button>
          ))}
        </div>
        <div>
          <h3 style={{ color: '#64ffda', fontSize: '16px' }}>Request log</h3>
          {requestLog.map((log, i) => (
            <div key={i} style={{ padding: '10px', borderRadius: '6px', background: '#1a1a2e', border: '1px solid #333', marginBottom: '8px', fontSize: '13px' }}>
              <code style={{ color: '#64ffda' }}>{log.path}</code>
              <div style={{ color: log.color, marginTop: '4px' }}>{log.result}</div>
            </div>
          ))}
          {requestLog.length === 0 && <p style={{ color: '#555' }}>Click a route to simulate a request</p>}
        </div>
      </div>
    </div>
  );
}

export default MiddlewareDemo;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. bcrypt is used for:

  2. 2. Refresh tokens are used for:

Hands-on tasks in the game

  • Code editor

    Create a control panel with a permissions system and middleware

  • Click in order

    Arrange the session-checking middleware syntax in Next.js

  • Code editor

    Create an email verification system with token generation, email sending, and verification endpoint

  • Vertical ordering

    Arrange the stages of authentication event auditing:

  1. Questionbcrypt is used for:
  2. QuestionRefresh tokens are used for:
  3. Coding taskPractice: Admin Panel with Middleware
  4. Click in orderSession-checking Middleware
  5. Coding taskPractice: Create an email verification system with token
  6. Put in orderStages of Authentication Event Auditing

Useful articles