Proxy
proxy.ts (called middleware.ts before Next.js 16) is a function that runs before a request reaches a route. It can redirect, rewrite, change headers or respond directly.
ts
// proxy.ts (project root or src/)
import { NextResponse, type NextRequest } from 'next/server';
export function proxy(request: NextRequest) {
if (!request.cookies.has('session')) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*'],
};Good use cases
- Redirects and rewrites based on the request (locale, A/B tests, old URLs).
- Setting headers (CSP, security headers) for a group of routes.
- Optimistic auth checks: no session cookie -> redirect to login.
What to avoid
- Slow data fetching: Proxy runs on every matched request, including prefetches.
- Being the only authorization layer: check access again where the data is read (Server Components, Server Actions, Route Handlers).
- For static redirects use
redirects()innext.config.tsinstead.
Details
- One
proxy.tsper project; split logic into modules and import them. - Since Next.js 16 it runs on the Node.js runtime by default.
fetchcache options (next.revalidate,next.tags) have no effect inside Proxy.
updated
did you know it?