Creating middleware in Next.js
From the Next.js cheat sheet · Middleware · verified Jul 2026
Creating middleware
typescript
// proxy.ts (Next.js 16 - was middleware.ts; in root or src/)
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
// Clone the request headers
const requestHeaders = new Headers(request.headers)
requestHeaders.set('x-custom-header', 'my-value')
// Create response with modified headers
const response = NextResponse.next({
request: {
headers: requestHeaders,
},
})
// Set response headers
response.headers.set('x-response-header', 'value')
return response
}
// Configure which paths proxy runs on
export const config = {
matcher: [
// Match all paths except static files and api
'/((?!api|_next/static|_next/image|favicon.ico).*)',
// Or specific paths
'/dashboard/:path*',
'/api/:path*',
],
}💡 proxy runs before every request - nodejs runtime, no edge
⚡ Place proxy.ts (was middleware.ts) in root or src/
📌 Can modify request/response
🟢 Use for auth, redirects, headers