Proxy in Next.js lets you run logic before a request completes. You can inspect the incoming request and modify the response by redirecting, rewriting, changing headers, or responding directly. This is useful for routing decisions, A/B testing, and global header control.
Proxy is not suitable for:
Note: Using fetch with options.cache, options.next.revalidate, or options.next.tags has no effect inside Proxy.
Create a proxy.ts (or proxy.js) file at the project root or inside src if applicable. It must be at the same level as pages or app. Only one proxy file is supported per project.
To keep things organized, you can split proxy logic into modules and import them into proxy.ts. This centralizes control and avoids performance issues from multiple proxy layers.
// proxy.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
return NextResponse.redirect(new URL('/home', request.url))
}
export const config = {
matcher: '/about/:path*',
}This example redirects any request to /about or its subpaths to /home. You can customize the matcher to target specific routes.
The matcher config defines which paths the proxy applies to. You can use wildcards like :path* to match nested routes.
Proxy in Next.js is a powerful tool for request-level control. Whether you're redirecting users, rewriting routes, or modifying headers, proxy.ts gives you centralized, performant control over how requests are handled before they reach your pages.