advanced

Authentication integration

Coordinate cookies, sessions, middleware, route handlers, server components, and authorization checks.

Auth in Next.js spans middleware gates, encrypted session cookies, server component session reads, route handler verification, and Server Action checks. No single file owns security — contracts must align.

Typical flow: middleware ensures a session cookie exists for protected paths; server code verifies session integrity and roles before data access; client shows UI state but cannot be the authority.

On interviews: explain HttpOnly cookies versus localStorage tokens, CSRF considerations for actions, and where authorization differs from authentication.

Common pitfalls: trusting client-side role flags, skipping server verification in actions, and middleware-only auth without handler checks.

The trade-off is convenience of auth libraries versus understanding session lifecycle end to end.

Checklist:

  • HttpOnly session cookies for browser auth.
  • Verify session on server for every mutation.
  • Align middleware matcher with protected routes.
  • Separate auth (who) from authorization (what).