Token Storage in SPAs: Security Trade-offs
What you'll learn: You'll understand where to store access and refresh tokens in a browser-based Single Page Application, and why each location has different security implications.
After completing the Authorization Code Flow with PKCE, your SPA receives tokens. Where you store them determines your attack surface.
The Storage Battleground
You have four main options for storing tokens in the browser:
localStorage
Persists across browser sessions and tabs. Vulnerable to XSS — any malicious script can read localStorage.getItem('access_token'). Once stolen, tokens can be sent to an attacker's server. The trade-off: convenient persistence, but high XSS risk.
sessionStorage
Similar to localStorage but cleared when the tab closes. Still vulnerable to XSS but with a slightly smaller attack window. Same convenience, same fundamental XSS vulnerability.
Memory-only (JavaScript variable)
Tokens stored only in runtime memory (like a React state or closure). Protected from XSS script theft since other scripts can't access your app's closure scope. The trade-off: tokens are lost on page refresh, requiring re-authentication or a refresh token strategy.
httpOnly Cookies
The backend sets cookies with httpOnly and Secure flags. JavaScript cannot access these cookies, protecting against XSS. However, they're vulnerable to CSRF attacks unless you implement SameSite attributes and anti-CSRF tokens. The trade-off: XSS-resistant but requires CSRF protection.
The Recommendation
Best practice: Store access tokens in memory, store refresh tokens in httpOnly cookies (handled by your backend). When the in-memory access token expires, use the cookie-based refresh token to get a new one silently. This balances security and user experience.
Key Takeaway: Token storage is a security trade-off between XSS and CSRF vulnerabilities—memory-only storage protects against XSS but requires refresh token flows, while cookies resist XSS but need CSRF defenses.