Next.jsMedium
How do you protect routes using middleware?
In proxy.ts, read the session cookie (optionally verify a signed token), and redirect unauthenticated users away from protected paths using a matcher or path checks. Treat this as an optimistic first gate for good UX; real authorization must still happen in pages, Route Handlers and Server Functions.
Implementation steps
- List protected and public routes (or protected prefixes).
- Read the session cookie from
request.cookies. - Optionally decrypt or verify it (a JWT signature check with
joseis fast). Avoid database lookups here. - Redirect to
/login?next=...if it is missing or invalid. - Redirect signed-in users away from
/loginand/signup. - Exclude static assets and prefetches with the matcher.
Why it is not enough on its own
- Server Functions are POST requests to the page route; if a matcher excludes that path, the action is unprotected.
- Matchers are easy to break during refactors.
- The cookie may exist but be revoked on the server.
- Role checks often need data (ownership of a document) that Proxy should not fetch.
The Next.js data security guidance is explicit: verify authentication and authorization inside every Server Function and data access function.
Defense in depth
- Proxy: fast redirect for unauthenticated users.
- Data Access Layer:
verifySession()plus permission checks on every read and write. - UI: hide controls users cannot use, purely for UX.
Libraries
Auth.js, Better Auth, Clerk and others provide Proxy helpers that do the optimistic check for you.
Code example
tsx
1// proxy.ts2import { NextResponse, type NextRequest } from "next/server";3import { jwtVerify } from "jose";45const key = new TextEncoder().encode(process.env.SESSION_SECRET);6const PUBLIC = ["/", "/login", "/signup", "/pricing"];78export async function proxy(request: NextRequest) {9 const { pathname } = request.nextUrl;10 const token = request.cookies.get("session")?.value;1112 let userId: string | undefined;13 if (token) {14 try {15 userId = (await jwtVerify(token, key)).payload.sub; // signature + expiry, no DB call16 } catch {}17 }1819 const isPublic = PUBLIC.includes(pathname);20 if (!userId && !isPublic) {21 return NextResponse.redirect(new URL(`/login?next=${encodeURIComponent(pathname)}`, request.url));22 }23 if (userId && (pathname === "/login" || pathname === "/signup")) {24 return NextResponse.redirect(new URL("/dashboard", request.url));25 }26 return NextResponse.next();27}2829export const config = { matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"] };
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.