Lesson 30 +10 XP

Next.js Middleware Fundamentals (middleware.ts)

Next.js Middleware Fundamentals (middleware.ts)

Middleware allows you to run code before a request is completed. Based on the incoming request, you can rewrite, redirect, modify request/response headers, or respond directly.

Middleware Execution Model

Middleware runs on the Edge Runtime (or Node.js runtime) before any route segment or page pre-rendering occurs. It sits between incoming network traffic and your application routes.

Client Request ──► [ Middleware (middleware.ts) ] ──► [ Route Handlers / Pages ]
                          │
                   Redirect / Rewrite / Header Edit

Creating a Root Middleware

Place a file named middleware.ts (or .js) in the root of your project (or inside src/):

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

export function middleware(request: NextRequest) {
  // 1. Log request path
  console.log('Incoming request path:', request.nextUrl.pathname);

  // 2. Add custom header to request
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set('x-middleware-executed', 'true');

  return NextResponse.next({
    request: {
      headers: requestHeaders,
    },
  });
}

// 3. Matcher configuration: Specify which paths trigger middleware!
export const config = {
  matcher: [
    /*
     * Match all request paths except for:
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    '/((?!_next/static|_next/image|favicon.ico).*)',
  ],
};

Route Matching with matcher

The config.matcher export accepts a path string or array of regex glob patterns to specify which routes invoke the middleware.

export const config = {
  // Run middleware ONLY on /dashboard/* and /api/* routes!
  matcher: ['/dashboard/:path*', '/api/:path*'],
};

Key Capabilities of Middleware

  • Route Protection: Check JWT auth tokens or cookies before granting access.
  • Bot Protection & Rate Limiting: Inspect IP addresses or user agents.
  • A/B Testing & Geo Routing: Rewrite URLs based on geolocation headers.
  • Header & Cookie Modification: Set security headers like Content Security Policy (CSP).

TL;DR

  • Create a single middleware.ts file in the root or src/ directory.
  • Export a function named middleware(request: NextRequest).
  • Export a config.matcher array to limit execution to specific routes.
  • Return NextResponse.next(), NextResponse.redirect(), or NextResponse.rewrite().