JWT cookies vs localStorage
October 13, 2026 · 12 min read
The JWT storage debate usually collapses to HttpOnly cookies versus localStorage. Cookies keep tokens off the JavaScript attack surface but introduce CSRF and size constraints. localStorage is simple for SPAs but makes any XSS a full session steal. Neither replaces server-side authorization.
HttpOnly cookies: higher baseline security
- Secure - Scripts cannot read HttpOnly cookies, reducing XSS token theft.
- Sent with every request - Browser attaches to same-site paths; configure path and domain narrowly.
- Expires with session - Use
Max-Ageor session cookies aligned with refresh policy. - Smaller capacity - ~4 KB per cookie; large JWT claims may not fit.
Pair with SameSite, CSRF tokens for state-changing routes, and HTTPS. Security rating for typical public web apps: high when implemented completely.
localStorage: developer ergonomics, XSS exposure
- Easy manual
Authorizationheaders in fetch. - Not sent automatically - Reduces accidental token leakage to third-party subdomains in some setups.
- Persists until cleared - Convenient for “remember me,” risky on shared devices.
- Larger quota - ~5 MB, but JWTs should stay small anyway.
Any script on your origin - including compromised npm packages - can read localStorage. Security rating: medium at best, dependent on XSS prevention.
Side-by-side summary
Choose cookies when you control same-site API routing and can implement CSRF defenses. Choose memory + backend-for-frontend when calling cross-origin APIs. Use localStorage only with eyes open about XSS and strong CSP.
Hybrid: memory access + HttpOnly refresh
Store short-lived access tokens in JavaScript memory (lost on refresh) and refresh tokens in HttpOnly cookies. Login endpoint sets cookie; SPA calls BFF to rotate. Logout clears both. Audit token byte size in the JWT decoder before committing to cookies.
FAQ
- Are cookies immune to XSS?
- HttpOnly cookies resist JS theft; XSS can still perform actions as the user. Defense in depth still matters.
- What about CSRF with cookies?
- Use SameSite, CSRF tokens, or custom headers on mutations.
- Can mobile apps use cookies?
- Mobile often uses secure storage or OAuth device flows; web cookie guidance targets browsers.
Related: JWT storage in browsers · JWT vs sessions · JWT security checklist