Stop at the door
Some pages are for staff only. proxy (proxy.js at the project root — called *middleware* before Next.js 16) runs before matching requests, so it can redirect visitors who aren't signed in before the page even renders.
proxy.js
import { NextResponse } from "next/server";
export function proxy(request) {
const session = request.cookies.get("session");
if (!session) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: "/admin/:path*",
};- Proxy is for quick, *optimistic* checks. Still verify the user in the page or server action that reads or changes data.
- For simple fixed redirects, use redirects in next.config instead.
- Auth libraries (Auth.js, Clerk, Better Auth) handle sessions and give you helpers for this.