Next.js Middleware

This page demonstrates the use of Next.js Middleware.

Middleware runs before a request is completed and can modify the response by rewriting, redirecting, or setting headers.

Headers Added by Middleware

Header NameValue
x-middleware-timestamp2026-01-14T19:47:54.685Z
x-middleware-exampletrue
x-middleware-cache-controlpublic, max-age=3600
x-sandbox-enabledtrue

Middleware Features

  • URL rewriting and redirecting
  • Adding or modifying headers
  • Setting cookies
  • Authentication and authorization checks
  • A/B testing and feature flags
  • Bot protection
  • Geolocation-based customization

Test Middleware Redirect

Visit /sandbox/redirect to see the middleware redirect in action.

Implementation Details

Middleware in Next.js is implemented in a middleware.ts file at the project root:

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

export function middleware(request: NextRequest) {
  // Modify the response
  const response = NextResponse.next()
  response.headers.set('x-custom-header', 'value')

  // Or redirect
  if (request.nextUrl.pathname === '/redirect') {
    return NextResponse.redirect(new URL('/new-page', request.url))
  }

  return response
}

// Optional config to specify on which routes middleware runs
export const config = {
  matcher: ['/sandbox/:path*'],
}