Script Valley
JWT & Session Auth: Deep Dive
Authentication FundamentalsLesson 1.3

how HTTP cookies work for auth

Set-Cookie header, cookie attributes, HttpOnly flag, Secure flag, SameSite policy, cookie lifecycle, CSRF exposure

How HTTP Cookies Work for Auth

HTTP Cookie Auth Flow

Cookies are the browser's built-in mechanism for persisting state across requests. The server sets them; the browser sends them automatically. That automatic sending is both their power and their risk.

When a user logs in, the server responds with a Set-Cookie header:

Set-Cookie: sessionId=abc123; HttpOnly; Secure; SameSite=Strict; Max-Age=3600

Each attribute matters:

  • HttpOnly: JavaScript cannot read this cookie. Blocks XSS-based token theft.
  • Secure: Cookie only sent over HTTPS. Never set without this in production.
  • SameSite=Strict: Cookie not sent on cross-site requests. Prevents CSRF attacks.
  • Max-Age / Expires: Controls lifetime. Without it, the cookie is session-only (deleted when the browser closes).

On every subsequent request to the same domain, the browser includes the cookie in the Cookie header automatically. The server reads it, looks up the session, and identifies the user.

The critical security rule: always set HttpOnly and Secure together on auth cookies. Omitting either one opens meaningful attack surfaces. SameSite=Lax is a safe default for most apps; use Strict when you do not need cross-site GET requests to carry credentials.

Up next

Bearer tokens and the Authorization header explained

Sign in to track progress