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 Name | Value |
|---|---|
| x-middleware-timestamp | 2026-01-14T19:47:54.685Z |
| x-middleware-example | true |
| x-middleware-cache-control | public, max-age=3600 |
| x-sandbox-enabled | true |
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*'],
}