SyntaxStudy
Sign Up
JavaScript Storage Security Best Practices
JavaScript Intermediate 5 min read

Storage Security Best Practices

Storage Security

localStorage is accessible to any JavaScript on the page (including third-party scripts and XSS attackers). Never store tokens, passwords, or sensitive personal data there.

Example
// BAD: Do not store auth tokens in localStorage
localStorage.setItem("authToken", jwt); // Accessible to XSS!

// BETTER: Store tokens in HttpOnly cookies (server-set)
// The browser sends them automatically, JS cannot read them

// Safe to store in localStorage:
localStorage.setItem("theme", "dark");
localStorage.setItem("lang", "en");
localStorage.setItem("cart", JSON.stringify(cartItems)); // Non-sensitive

// Sanitize on read — never trust stored data
const theme = ["light", "dark"].includes(localStorage.getItem("theme"))
  ? localStorage.getItem("theme")
  : "light";
Pro Tip

Treat localStorage like a public notice board — never put anything there you would not want every script on the page to read.