Advanced
Advanced
Proxy and Request Boundaries
Use Next.js 16 Proxy for lightweight request interception without moving business logic out of the app.
30 min
2 sections
proxy
auth
routing
security
1
2
01. Proxy replaced middleware naming
Section 1 of 2
Next.js 16 uses the Proxy convention for request interception. Keep Proxy lightweight: routing, coarse gates, headers, and rewrites. Authorization, data ownership, and business rules still belong in server functions and route handlers.
typescript
// proxy.ts
import { NextResponse, type NextRequest } from "next/server";
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
const session = request.cookies.get("session")?.value;
if (pathname.startsWith("/app") && !session) {
const loginUrl = new URL("/login", request.url);
loginUrl.searchParams.set("returnTo", pathname);
return NextResponse.redirect(loginUrl);
}
const response = NextResponse.next();
response.headers.set("x-request-path", pathname);
return response;
}
export const config = {
matcher: ["/app/:path*", "/admin/:path*"],
};Back to Course