localStorage vs httpOnly Cookies for JWT
localStorage
Pros
- Easy JavaScript access for SPA API calls
- No CSRF concerns (not sent automatically)
- Works across subdomains with manual header
- Simple implementation for frontend developers
Cons
- Accessible to any JavaScript — XSS steals token
- No httpOnly protection
- Persists until explicitly cleared
- Vulnerable to third-party script attacks
httpOnly Secure Cookies
Pros
- Inaccessible to JavaScript — XSS cannot read token
- Automatic transmission with SameSite policy
- Secure flag enforces HTTPS only
- Industry recommended for refresh tokens
Cons
- Requires CSRF protection (SameSite, tokens)
- More complex server-side cookie configuration
- Cross-domain setups need careful CORS/cookie setup
- Less convenient for pure SPA architectures
Verdict
Store refresh tokens in httpOnly, Secure, SameSite cookies — this is the industry consensus for web applications. Avoid localStorage for any token an XSS attack could steal. If you must use localStorage for access tokens, keep them very short-lived (minutes) and treat XSS prevention as mandatory, not optional. For mobile and API-only clients, secure platform storage replaces both patterns. Never store JWT signing secrets in either location.
Related Tools
Deeper Reading
Frequently Asked Questions
Why is localStorage dangerous for JWTs?
Any XSS vulnerability lets an attacker run JavaScript that reads localStorage and exfiltrates your token.
How do I prevent CSRF with cookie-stored JWTs?
Use SameSite=Lax or Strict, require custom headers for state-changing requests, or implement CSRF tokens.