skip to content

Auth Gating Patterns

Checking for a session cookie in middleware gives you a cheap redirect to login, but it is not authorization — the edge often can't safely verify a session. Interviewers ask what you'd still enforce inside the route or action.

part ofNext.jsoverview, primer and where to startread it →
on this pageshow

explore

questions

4

In a Next.js app, middleware reads a role claim from the session cookie and admits only role=admin to /admin/*, and the team now treats every page and Server Action under /admin as trusted. Which authorization decisions can that middleware check not make, and where do you enforce them instead?

level: seniorimportance: must knowfreq 58%

basics

~20 s

Middleware sees a URL, headers and cookies before the route resolves, so it can gate a route family but cannot decide whether this user may read this record, and its role claim is a snapshot that survives revocation. Enforce per-resource authorization in the code that queries the data.

open as a page

In a Next.js App Router app, middleware sends a signed-out visitor from /dashboard/settings to /login. How do you get that visitor back to /dashboard/settings after they sign in, and what must you check about the stored destination before you redirect to it?

level: juniorimportance: should knowfreq 52%

basics

~20 s

Store the original path in a query parameter on the login URL: read it from request.nextUrl in middleware, redirect to /login?callbackUrl=/dashboard/settings, then after sign-in redirect back only if that value is a relative, same-origin path.

open as a page

You own authentication for a Next.js App Router codebase that a dozen product teams add routes and Server Actions to. How do you decide what the middleware gate is responsible for versus what each feature must enforce, and how do you keep an unprotected route from shipping?

level: principalimportance: should knowfreq 36%

basics

~20 s

Make middleware a deny-by-default gate for signed-in-ness only, and route every data access through one session-verifying module. Keep routes safe by construction — a negative matcher, an enforced import boundary, and tests that enumerate routes — not by asking teams to remember.

open as a page