Last Updated: November 21, 2025
Middleware Focus
| Purpose | Approach |
|---|---|
Routing
|
Use middleware.ts with NextResponse.rewrite or redirect. |
Headers
|
Copy or strip headers via NextResponse.next() and response.headers. |
Edge runtime
|
No Node APIs—use Web Crypto and fetch instead. |
Matchers
|
Limit files with export const config = { matcher: ['/dashboard/:path*'] }. |
Key APIs
import { NextResponse } from 'next/server'
Construct responses that run on the edge.
export function middleware(request)
Run before every matched request to inspect cookies or rewrite.
return NextResponse.rewrite(new URL('/app', request.url))
Move traffic without a client redirect.
request.nextUrl.searchParams.set('utm_source', 'middleware')
Augment URLs before continuing.
Summary
Middleware lets you guard routes, mutate headers, and rewrite traffic at the edge—keep it fast by avoiding heavy computations.
💡 Pro Tip:
Test middleware via next dev and check both edge and node runtimes to catch mismatched globals.