Authentication Tokens in localStorage
Storing JWT tokens, session tokens, or API keys in localStorage makes them accessible to any JavaScript running on the page, including XSS payloads.
How It Works
localStorage is accessible to any JavaScript running on the same origin. If an attacker achieves even a minor XSS vulnerability, they can extract all tokens with a single line: document.cookie is protected by HttpOnly, but localStorage has no such protection. Stolen tokens allow session hijacking, account takeover, and API abuse. Unlike cookies, localStorage values are never automatically sent with requests, so developers must manually attach them — often in ways that expose them to CSRF or XSS. Tokens in localStorage also persist after the browser is closed, extending the attack window.
// After login
const { token } = await response.json();
localStorage.setItem('auth_token', token);
// On every request
fetch('/api/data', {
headers: { Authorization: `Bearer ${localStorage.getItem('auth_token')}` }
});// Server sets HttpOnly cookie after login
// In API route:
res.setHeader('Set-Cookie', serialize('session', token, {
httpOnly: true,
secure: true,
sameSite: 'lax',
path: '/',
maxAge: 60 * 60 * 24 * 7
}));
// Client requests automatically include the cookie
fetch('/api/data', { credentials: 'include' });Real-World Example
In 2022, an XSS vulnerability in a popular React dashboard allowed attackers to steal JWTs from localStorage of admin users. The tokens had long expiration times (30 days), giving attackers persistent access to admin panels and customer data.
How to Prevent It
- Store tokens in HttpOnly, Secure cookies instead of localStorage
- Set SameSite=Lax or Strict on authentication cookies
- Use short token expiration times with refresh token rotation
- Implement Content Security Policy to reduce XSS attack surface
Affected Technologies
Data Hogo detects this vulnerability automatically.
Scan Your Repo FreeRelated Vulnerabilities
dangerouslySetInnerHTML Without Sanitization
highUsing React's dangerouslySetInnerHTML with unsanitized user input allows attackers to inject malicious scripts that execute in other users' browsers.
__NEXT_DATA__ Secrets Exposure
highNext.js page props passed through getServerSideProps or getStaticProps leak sensitive data like API keys, database URLs, or internal configuration via the __NEXT_DATA__ script tag.
Source Maps Exposed in Production
mediumJavaScript source map files (.map) are publicly accessible in production, revealing the complete original source code including comments, variable names, and internal logic.
Open CORS in Next.js API Routes
mediumNext.js API routes configured with Access-Control-Allow-Origin: * allow any website to make authenticated cross-origin requests, enabling CSRF-like attacks.