← Next.js learning path
Next.js · Module 8 of 10

Authentication and middleware

Protect pages and APIs with sessions and middleware.

📖 Key ideas

  1. Auth libraries: Auth.js (NextAuth), Clerk, Firebase Auth, Supabase Auth.
  2. Store sessions in secure httpOnly cookies.
  3. Middleware (middleware.ts / proxy) runs before requests to redirect or rewrite.
  4. Check auth again in server components, actions and route handlers.
  5. Never trust client-only checks.
💡 Real-life example: Middleware is a gatekeeper at the colony gate; each house (page) should still lock its own door.
Auth.jsAuthentication library for Next.js
MiddlewareCode that runs before a request is handled
SessionServer-known login state
RedirectSend the user to another URL