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.
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.
// 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";
Treat localStorage like a public notice board — never put anything there you would not want every script on the page to read.
More in JavaScript