Next.jsWeb DevelopmentSoftware EngineeringSystems Design

Middleware in Next.js: A Comprehensive Guide

A reference guide to middleware in Next.js: what it intercepts in the request and response cycle, how to set it up, advanced patterns, and the upgrade path.

Aerial view of a city at night, split by a band of blue and magenta light trails along a highway.
Table of Contents (20)

Middleware in Next.js lets developers intercept, modify, and control the flow of requests and responses in an application. This guide runs from the basics to advanced techniques.

Complete examples are in the associated Gist: https://gist.github.com/zachshallbetter.

Table of Contents

  • Understanding Middleware

  • Using Middleware in Next.js

  • Middleware in Next.js

  • Advanced Middleware Techniques

  • Middleware Upgrade Guide


1. Understanding Middleware

What is Middleware?

Middleware intercepts and manipulates the request-response cycle. It consists of actions that change incoming requests or outgoing responses to fit your application’s needs.

In Next.js, middleware lets you shape the behavior of your application at a granular level without extra steps.

Middleware’s job is to intercept and manipulate HTTP requests and responses as they pass through the application.

The examples below use both Next.js 13 and Javascript.

Routing

Routing control redirects requests to different URLs and enforces URL patterns. It’s especially useful for complex routing scenarios.

// Next.js
// Redirect requests from the old URL to the new one
export function redirectMiddleware(request: NextRequest) {
  return NextResponse.redirect('/new-url');
}
// Javascript
function redirectMiddleware(request) {
  // Redirect to the new URL
  window.location.href = '/new-url';
  // Return an empty response as this code won't execute after redirection
  return {
    status: 204, // No content
    body: '',
  };
}

Middleware can manage cookies in both incoming requests and outgoing responses. This is essential for tasks like setting user session cookies, reading cookies for authentication, or deleting cookies when a user logs out.

Tyexport function cookieManagementMiddleware(request: NextRequest) {
  const response = NextResponse.next();
  response.cookies.set('myCookie', '123');
  return response;
}
function cookieManagementMiddleware(request) {
  const response = {
    status: 200,
    cookies: {
      myCookie: '123',
    },
  };
  return response;
}

Authentication

Middleware can check whether a user is authenticated before granting access to specific routes or resources.

In the example below, a middleware function checks session cookies when a user tries to reach a protected route. If the user isn’t authenticated, they’re redirected to a login page or denied access.

// Using Next.js
export function authenticationMiddleware(request: NextRequest) {
  if (!request.headers.cookie?.includes('authenticated=true')) {
    // Redirect to the login page
    return NextResponse.redirect('/login');
  }
  return NextResponse.next();
}
// Using Javascript
function authenticationMiddleware(request) {
  if (!(request.headers.cookie && request.headers.cookie.includes('authenticated=true'))) {
    // Redirect to the login page
    window.location.href = '/login';
    // Return an empty response as this code won't execute after redirection
    return {
      status: 204, // No content
      body: '',
    };
  }
  // Continue to the next middleware or route handler
  return {
    status: 200,
  };
}

Logging

Middleware can log incoming requests, including method, URL, headers, and timestamp. The logs help with diagnosing issues, tracking user activity, and analyzing performance.

export function loggingMiddleware(request: NextRequest) {
  console.log(`Received ${request.method} request to ${request.url} at ${new Date()}`);
  return NextResponse.next();
}
function loggingMiddleware(request) {
  console.log(`Received ${request.method} request to ${request.url} at ${new Date()}`);
  return {
    status: 200, // Continue to the next middleware or route handler
  };
}

Response Customization

Middleware can customize response headers, status codes, or content based on conditions. For instance, you might set custom headers that give the client extra information or adjust the content dynamically.

export function customHeadersMiddleware(request: NextRequest) {
  const response = NextResponse.next();
  response.headers.set('X-Custom-Header', 'Hello, Middleware!');
  response.cookies.set('myCookie', '123');
  return response;
}
function customHeadersMiddleware(request) {
  const response = {
    status: 200,
    headers: {
      'X-Custom-Header': 'Hello, Middleware!',
    },
    cookies: {
      myCookie: '123',
    },
  };
  return response;
}

2. Middleware in Next.js

The Middleware File

In Next.js, middleware is defined in a file typically named middleware.ts (or .js) in the root of your project. Here's a basic example:

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

export function myMiddleware(request: NextRequest) {
  // Your Middleware logic here
  return NextResponse.next(); // Pass control to the next Middleware or route handler
}

NextResponse API

NextResponse is the Next.js API for working with responses in middleware. It has methods for redirecting requests, rewriting responses, and setting headers and cookies.

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

export function myMiddleware(request: NextRequest) {
  // Redirect the request to a different URL
  return NextResponse.redirect('/new-url');
  // Rewrite the response to display content from a different URL
  return NextResponse.rewrite('/new-content');
  // Set response headers and cookies
  const response = NextResponse.next();
  response.headers.set('X-Custom-Header', 'Hello, Middleware!');
  response.cookies.set('myCookie', '123');
  return response;
}

3. Using Middleware in Next.js

Middleware functions in Next.js have access to both the incoming request and the response. You can modify these objects to tailor the behavior of your application.

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

export function authenticationMiddleware(request: NextRequest) {
  // Check if the user is authenticated
  if (!request.headers.cookie?.includes('authenticated=true')) {
    return NextResponse.redirect('/login');
  }
  return NextResponse.next(); // Continue to the next Middleware or route handler
}

Setting Headers and Cookies

Middleware can manipulate headers and cookies in incoming requests and outgoing responses, which is useful for customizing the response or managing user sessions.

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

export function customHeadersMiddleware(request: NextRequest) {
  const response = NextResponse.next();
  response.headers.set('X-Custom-Header', 'Hello, Middleware!');
  response.cookies.set('myCookie', '123');
  return response;
}

Producing Custom Responses

Middleware can produce responses directly by returning a Response or NextResponse instance, so your own logic controls what the client receives.

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

export function customResponseMiddleware(request: NextRequest) {
  if (/* Some condition */) {
    return new Response('Custom error message', { status: 400 });
  }
  return NextResponse.next();
}

4. Advanced Middleware Techniques

Intercepting API Calls

Intercepting API calls is one use case. Middleware can modify API request headers, cache responses, or mock API calls for testing.

Modifying Request Headers

Middleware can modify the headers of outgoing API requests, often to add authentication tokens, API keys, or other needed information before the request is sent.

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

export function apiInterceptorMiddleware(request: NextRequest) {
  // Modify the API request headers
  request.headers.set('Authorization', 'Bearer myAccessToken');

  // Cache API responses for improved performance
  // Implement caching logic here

  return NextResponse.next();
}

Caching API Responses

Caching API responses in middleware improves performance, reduces the load on external APIs, and speeds up repeat requests for the same data.

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

export function apiInterceptorMiddleware(request: NextRequest) {
  // Check if the response is already cached
  const cachedResponse = /* Implement caching logic here */;

  if (cachedResponse) {
    // If cached, return the cached response
    return cachedResponse;
  } else {
    // If not cached, make the API request and cache the response
    const apiResponse = /* Make the API request */;

    // Cache the response for future use
    /* Cache the response */

    return apiResponse;
  }
}

Mocking API Calls for Testing

Middleware can also mock API calls during testing, so tests don’t depend on external services and run faster and more reliably.

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

export function apiMockMiddleware(request: NextRequest) {
  if (process.env.NODE_ENV === 'test') {
    // In a testing environment, return a mocked response
    return new Response(JSON.stringify({ mockData: true }), {
      status: 200,
      headers: {
        'Content-Type': 'application/json',
      },
    });
  } else {
    // In other environments, continue to the next Middleware or route handler
    return NextResponse.next();
  }
}

5. Middleware Upgrade Guide

If you’ve used middleware in earlier versions of Next.js and plan to upgrade to version 12.2 or later, the Middleware API has changed, and your existing middleware code might need updating. The official Next.js documentation on Middleware has detailed upgrade instructions and official examples.