Auth Patterns Overview
Auth in Next.js App Router: cookies/sessions, middleware gates, server checks, and avoiding client-only security theater.
- nextjs
- auth-patterns
Authentication in Next is not a single API — it is a pattern: establish a session, send it on requests (usually httpOnly cookies), verify on the server, and gate UI and data.
Docs: Authentication, libraries like Auth.js.
Core flow
- User signs in via Server Action or Route Handler.
- Server sets httpOnly, Secure, SameSite session cookie.
- Middleware optionally redirects unauthenticated users away from private paths.
- Server Components / Actions re-verify session before returning private data.
- Client never treats “I have React state saying logged in” as authoritative.
// Server Component
import { cookies } from 'next/headers';
export default async function AccountPage() {
const session = await getSessionFromCookie(await cookies());
if (!session) {
redirect('/login');
}
const user = await db.users.get(session.userId);
return <Profile user={user} />;
}
Middleware role
Lightweight gate only:
// pseudo
if (!request.cookies.get('session') && isProtected(path)) {
return NextResponse.redirect(loginUrl);
}
Full permission checks (roles, entitlements) belong next to data access.
Client components
Client UI can hide buttons, but every mutation and private fetch must authorize on the server. Client-only auth is security theater.
Third-party providers
OAuth callbacks usually hit Route Handlers; sessions stored as cookies or tokens. Mind environment variables for secrets (AUTH_SECRET, client ids).
Interview out-loud
“I store sessions in httpOnly cookies, gate routes in middleware for UX, and always re-check auth in Server Components and Server Actions before private data. Client state never authorizes by itself. Secrets stay in server env.”
Related on this site
Further reading
Edge cases worth rehearsing
Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.
Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.
When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.
Edge cases worth rehearsing
Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.
Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.
When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.
Related guides
- Caching in Next.js OverviewNext.js caching layers: request memoization, data cache, full route cache, and router cache — what invalidates each.
- Client Components in Next.jsClient Components in the App Router: use client, hydration, bundling boundaries, and patterns that keep JS small.
- Data Fetching Patterns App RouterFetch data in Server Components with async/await and fetch caching: colocation, parallel requests, and client fallbacks.
- Deploying Next on VercelDeploy Next.js on Vercel: git integration, env vars, previews, build cache, and production checklist.
- Edge Runtime TradeoffsEdge Runtime vs Node.js in Next.js: cold starts, API limits, middleware, and when Node is the right default.