Skip to the page

Mutations, APIs and the request layer · senior

Authentication and authorisation in the App Router

Keep public pages static and do auth checks close to the data: an optional optimistic cookie check in proxy, a Data Access Layer whose verifySession() runs in every data function, Server Action and Route Handler, and DTOs that return only safe fields.

The notes

What you must know

  • Authentication (who you are), session management (remembering it), authorisation (what you may do) are separate concerns; prefer an auth library (Auth.js, Better Auth, Clerk, etc.).
  • Sessions: stateless (signed/encrypted cookie, e.g. JWT via jose/iron-session) or database sessions (cookie holds an encrypted session id). Cookies set on the server with HttpOnly, Secure, SameSite=Lax, expiry and path.
  • Data Access Layer: import "server-only"; verifySession = cache(async () => { ... redirect("/login") }) wrapped in React.cache to dedupe within a render. Note: React.cache does nothing in Server Actions and Route Handlers.
  • Call verifySession() in data functions, Server Actions and Route Handlers, not only in pages.
  • Do not rely on layouts for auth: layouts do not re-render on navigation, and hiding children in a layout does not stop nested segments, parallel slots or Server Actions from running.
  • Optimistic checks in proxy read only the cookie (no DB), and protect static routes that share data.
  • Keep marketing pages fast: do not read cookies in the root layout (it would make every route request-time); read the session in a small component inside Suspense or only in the dashboard segment.
  • Client Components cannot import the DAL; check on the server and pass the minimal data down.

The red pen

Common traps: mistake → fix

  • Mistake: "The middleware/proxy handles auth"

    Fix: it is only an optimistic first check.

  • Mistake: "return null in the dashboard layout if not logged in"

    Fix: nested routes and actions are still reachable.

  • Mistake: "Read the session in the root layout"

    Fix: makes the whole site dynamic and slow.

Easy to hard

Questions interviewers ask, easy to hard

  1. Our marketing site and logged-in dashboard live in one Next.js app. How do you keep the dashboard secure and the marketing pages fast?
  2. Where exactly do auth checks go?
  3. Why is checking auth in a layout not enough?
  4. Stateless JWT cookie vs database sessions?
  5. What are a Data Access Layer and DTOs?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview