How do you protect routes using middleware?
Use proxy.ts as an optimistic gate: read the session cookie, redirect signed-out users from protected paths and signed-in users away from auth pages. Then enforce real authorization close to the data, because Proxy can be bypassed by matcher gaps and does not know about resource ownership.
A layered approach
- Proxy (UX layer): cookie present and token valid? If not, redirect to
/login. Keeps protected pages from flashing. - Page / layout (render layer):
const session = await verifySession(); if (!session) redirect("/login"). - Data Access Layer (security layer): every query and mutation checks the user's permission for the specific record.
- Server Functions and Route Handlers: check the session at the start of each one.
Why layers
- Server Functions are invoked as POSTs to the page URL, so a matcher that excludes the page skips Proxy for its actions.
- Layouts do not re-run on client navigation between their children, so a layout-only check can miss cases.
- Proxy should not query the database on every request.
Role-based routes
Proxy can redirect by a role claim in a signed token (/admin requires role=admin), but double-check in the data layer because roles can change after the token was issued.
Auth library helpers
Auth.js exports auth as a Proxy wrapper, Clerk provides clerkMiddleware() with createRouteMatcher, and Better Auth reads the session cookie with a helper. They all do the optimistic check; you still authorize data access yourself.
With authInterrupts
In pages, unauthorized() and forbidden() (experimental) render unauthorized.tsx or forbidden.tsx with 401/403 status, as an alternative to redirecting.
Code example
1// proxy.ts - optimistic gate2import { NextResponse, type NextRequest } from "next/server";3import { decrypt } from "@/lib/session-token"; // verifies signature only, no DB45const protectedPrefixes = ["/dashboard", "/admin"];67export async function proxy(req: NextRequest) {8 const path = req.nextUrl.pathname;9 const session = await decrypt(req.cookies.get("session")?.value);1011 if (protectedPrefixes.some((p) => path.startsWith(p)) && !session?.userId) {12 return NextResponse.redirect(new URL("/login", req.nextUrl));13 }14 if (path.startsWith("/admin") && session?.role !== "admin") {15 return NextResponse.redirect(new URL("/dashboard", req.nextUrl));16 }17 return NextResponse.next();18}1920export const config = { matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"] };2122// app/admin/users/actions.ts - real check close to the data23// "use server";24// export async function banUser(id: string) {25// const s = await verifySession();26// if (s?.role !== "admin") throw new Error("Forbidden");27// await db.user.update({ where: { id }, data: { banned: true } });28// }
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.