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

  1. List protected and public routes (or protected prefixes).
  2. Read the session cookie from request.cookies.
  3. Optionally decrypt or verify it (a JWT signature check with jose is fast). Avoid database lookups here.
  4. Redirect to /login?next=... if it is missing or invalid.
  5. Redirect signed-in users away from /login and /signup.
  6. 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.ts
2import { NextResponse, type NextRequest } from "next/server";
3import { jwtVerify } from "jose";
4
5const key = new TextEncoder().encode(process.env.SESSION_SECRET);
6const PUBLIC = ["/", "/login", "/signup", "/pricing"];
7
8export async function proxy(request: NextRequest) {
9 const { pathname } = request.nextUrl;
10 const token = request.cookies.get("session")?.value;
11
12 let userId: string | undefined;
13 if (token) {
14 try {
15 userId = (await jwtVerify(token, key)).payload.sub; // signature + expiry, no DB call
16 } catch {}
17 }
18
19 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}
28
29export 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.

Open in study app