ESC

Type to search the knowledge base.

Auth Patterns Overview

Auth in Next.js App Router: cookies/sessions, middleware gates, server checks, and avoiding client-only security theater.

advanced3 min read
  • 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

  1. User signs in via Server Action or Route Handler.
  2. Server sets httpOnly, Secure, SameSite session cookie.
  3. Middleware optionally redirects unauthenticated users away from private paths.
  4. Server Components / Actions re-verify session before returning private data.
  5. 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.”

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