IntermediateTECHNICAL
In a secure dashboard built with Next.js, how would you handle authentication and authorization end-to-end? Include where you’d verify sessions/tokens, how you’d protect sensitive pages and API routes, and how you’d avoid common security pitfalls in the browser.
Next.js Developer
General

Sample Answer

For a secure dashboard, I like to keep auth checks as close to the edge as possible. Typically I’ll use NextAuth or a custom JWT/session implementation with an `auth` middleware at `middleware.ts` to gate all `/dashboard` and `/api/private` routes. That middleware verifies an HttpOnly, secure, sameSite cookie, decodes the session, and redirects unauthenticated users before the page even renders. In the App Router, protected layouts are server components that call a shared `getSession` helper. That lets me do role checks (e.g. admin vs read-only) and pass down a minimal user object. Sensitive API routes re-validate the session and authorization on every request; no trusting client-side flags. On one internal tool with ~500 active users, this setup blocked 100% of unauthorized access attempts we saw in logs and cut auth-related bugs by about 60%. I also avoid localStorage for tokens, use CSRF tokens for mutations, and implement strict CSP headers.

Keywords

Use middleware for early auth checks on pages and APIsStore tokens in HttpOnly secure cookies, not localStorageRe-validate session and roles on server for every sensitive operationLayer in CSRF protection and sensible security headers like CSP