Next.js proxy.ts: Redirects, Auth Checks and Rewrites at the Edge of Your App
Sometimes you need to act on a request before any page renders: redirect signed-out users, rewrite a path, or add a header. In Next.js 16 this file is called proxy.ts; earlier versions called it middleware.ts and the idea is the same.
A basic proxy
// proxy.ts (project root, or src/proxy.ts)
import { NextResponse, type NextRequest } from 'next/server';
export function proxy(request: NextRequest) {
const session = request.cookies.get('session')?.value;
if (!session && request.nextUrl.pathname.startsWith('/dashboard')) {
const login = new URL('/login', request.url);
login.searchParams.set('next', request.nextUrl.pathname);
return NextResponse.redirect(login);
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*', '/settings/:path*'],
};
Useful patterns
Rewrites serve different content without changing the URL, for example A/B tests or multi-tenant sites:
const host = request.headers.get('host'); // acme.example.com
const tenant = host?.split('.')[0];
return NextResponse.rewrite(new URL(`/tenants/${tenant}${request.nextUrl.pathname}`, request.url));
Response headers:
const res = NextResponse.next();
res.headers.set('X-Frame-Options', 'DENY');
return res;
Rules of thumb
- Keep it fast. It runs on every matching request, so avoid slow database calls.
- Use
matcherto skip static files and images. - A cookie check here is an optimistic redirect for UX, not your security. Still check authorisation in the page, Server Action or API route that reads the data.
- Migrating from
middleware.ts? Rename the file and the exported function toproxy; Next.js provides a codemod.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.