Back to 20 Concepts
sessions-cookies • Intermediate
Storage & Transport Security: HttpOnly SameSite Cookies vs Bearer Tokens
Storing JWTs in LocalStorage leaves them vulnerable to instant theft via Cross-Site Scripting (XSS). HttpOnly, Secure, SameSite=Strict cookies cannot be accessed by malicious JavaScript, completely eliminating XSS token exfiltration.
Intuitive Mental Model
The Safe Deposit Box in the Bank Vault: LocalStorage is leaving your wallet on the coffee table (any JavaScript on the page can steal it). An HttpOnly cookie is putting your money in a bank vault that only the armored delivery truck (the browser HTTP request engine) can access.
Architecture Blueprint & CodeProduction Standard
// Secure Cookie Header (Set by Backend): // Set-Cookie: session_token=abc123xyz; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=604800; Domain=corp.io // 1. HttpOnly: Blocks document.cookie access in JavaScript (Stops XSS token theft!) // 2. Secure: Transmitted strictly over encrypted HTTPS // 3. SameSite=Lax: Prevents Cross-Site Request Forgery (CSRF) on cross-origin POSTs
Key Architectural Takeaways
- •HttpOnly: Prevents any script on the page (XSS shims, compromised npm packages) from reading the session credential.
- •SameSite=Strict vs Lax: SameSite=Lax permits top-level navigation links while blocking cross-origin form submissions and image tags.
- •Token Storage Rule: Store Refresh Tokens in HttpOnly cookies and keep Access Tokens in memory.
Common Architectural Pitfall
Storing long-lived JWT access/refresh tokens in localStorage or sessionStorage where any XSS vulnerability immediately compromises the user account.
Production Best Practice
Store authentication tokens in HttpOnly, Secure, SameSite=Lax cookies.