By default, JavaScript data disappears when you close or refresh the page. localStorage lets you store data in the browser that persists across page loads, tab closes, and even browser restarts.
Copy
// SavelocalStorage.setItem("username", "sarah_chen");// Retrieve (even after closing and reopening the browser)const username = localStorage.getItem("username");console.log(username); // "sarah_chen"
// Store a valuelocalStorage.setItem("theme", "dark");// Get a valueconst theme = localStorage.getItem("theme"); // "dark"// Remove a specific valuelocalStorage.removeItem("theme");// Clear everythinglocalStorage.clear();
That’s the entire API. Four methods, all synchronous, all straightforward.
Since localStorage only stores strings, you need JSON.stringify() and JSON.parse():
Copy
// Save an objectconst user = { name: "Sarah Chen", role: "admin", theme: "dark" };localStorage.setItem("user", JSON.stringify(user));// Load it backconst saved = localStorage.getItem("user");const loadedUser = JSON.parse(saved);console.log(loadedUser.name); // "Sarah Chen"
Copy
// Save an arrayconst favorites = ["React", "FastAPI", "TypeScript"];localStorage.setItem("favorites", JSON.stringify(favorites));// Load it backconst loadedFavorites = JSON.parse(localStorage.getItem("favorites"));console.log(loadedFavorites); // ["React", "FastAPI", "TypeScript"]
If you forget JSON.stringify() when saving an object, you’ll store the useless string "[object Object]". Always stringify objects before saving and parse after loading.
localStorage.getItem() returns null if the key doesn’t exist. Handle this:
Copy
// This returns null if "settings" doesn't exist (it does NOT crash)const settings = JSON.parse(localStorage.getItem("settings"));console.log(settings); // null// ✅ Safe with fallbackconst settings = JSON.parse(localStorage.getItem("settings")) || { theme: "light", fontSize: 14,};
If the stored value is invalid JSON (for example, someone manually edited it in DevTools), JSON.parse()will throw. Use try/catch if the data might be corrupted.
Always provide a fallback when loading from localStorage. The data might not exist yet (first visit), or the user might have cleared their browser data.
sessionStorage works exactly like localStorage but data is cleared when the browser tab closes. Use it for truly temporary data like “which tab is selected” or “scroll position.”
Sensitive data — never store passwords, tokens, or personal data. localStorage is readable by any JavaScript on the page (including malicious scripts).
Large data — the ~5-10 MB limit makes it unsuitable for images, videos, or large datasets.
Data that must sync across devices — localStorage is per-browser, per-device. Use your backend database for data that should follow the user.
Critical application data — users can clear localStorage at any time. Don’t store anything your app can’t recreate from the backend.
Never store authentication tokens in localStorage. It’s vulnerable to XSS attacks — any JavaScript on the page can read it. Use HTTP-only cookies for auth tokens instead.
You’ve covered the DOM and browser APIs — selecting elements, modifying the page, handling events, working with forms, and persisting data. These are the building blocks that every framework builds on.Next up: React. You’ll see how React takes everything you’ve learned — DOM manipulation, event handling, state management — and wraps it in a component-based architecture that scales to real applications.