Overview

Middleware runs before a request is completed. It can modify the request, enforce authentication, redirect users, or handle logging before the request reaches a page or API route. Middleware is executed on the Edge Runtime, making it lightweight and efficient.

Middleware Placement

Middleware should be placed in the root directory of a Next.js project.

How Middleware Works

  1. A user requests a page or resource.
  2. Middleware intercepts the request.
  3. It can modify the request, respond directly, or allow it to proceed.
  4. If allowed, the request continues to the intended page or API route.

Basic Middleware Example

// middleware.ts
import { NextResponse } from "next/server";

export function middleware(request: Request) {
  console.log("Middleware executed");

  return NextResponse.next(); // Allows the request to continue
}

Middleware is automatically executed on every request unless configured otherwise.

Common Use Cases

Authentication and Access Control

Middleware can check if a user is authenticated before allowing access to a protected route.

import { NextResponse } from "next/server";

export function middleware(request: Request) {
  const token = request.cookies.get("authToken");

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

  return NextResponse.next();
}

This ensures that only authenticated users can access certain pages.

Redirects