Web Storage
Store data in the browser with localStorage, sessionStorage, and IndexedDB.
What you'll learn
- The difference between localStorage, sessionStorage, and IndexedDB
- How to read, write, and remove items with the Storage API
- When to use each storage mechanism and their size limits
- Why sensitive data should not go in localStorage (XSS risk)
Concept
Web Storage
Browsers can store data on the user's device, so it persists across page reloads and sessions. There are three main options — localStorage, sessionStorage, and IndexedDB — each with different lifetimes, capacities, and use cases. Choosing the right one is a key decision in web app design.
localStorage
localStorage stores key-value pairs as strings. Data persists indefinitely — it survives page reloads, browser restarts, and even computer reboots — until explicitly cleared. The API is simple:
localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme"); // "dark"
localStorage.removeItem("theme");
The capacity is typically 5–10 MB per origin. Because it is synchronous, large reads can block the main thread. localStorage is perfect for user preferences (theme, language), small cached data, and feature flags. It is never sent to the server — it is purely client-side.
sessionStorage
sessionStorage has the same API as localStorage, but data is cleared when the tab or window closes. It is useful for temporary state that should not persist: a multi-step form's progress, a scroll position to restore on back-button, or a temporary filter. If the user opens the same page in a new tab, each tab has its own sessionStorage — they do not share.
IndexedDB
IndexedDB is a full client-side database — it stores structured data, supports indexes and queries, and handles large amounts (hundreds of MB or more). It is asynchronous (does not block the UI) and can store objects, files, and blobs, not just strings. The API is more complex than localStorage, so many developers use a wrapper library like idb or localForage. Use IndexedDB for offline-first apps, large caches, and storing data that needs querying.
Security Warning
Never store sensitive data in localStorage. Any JavaScript running on the page — including injected XSS scripts — can read it. Passwords, session tokens, and personal data belong in httpOnly cookies (which JavaScript cannot access) or in server-side sessions. localStorage is for non-sensitive preferences and caches only. This is one of the most common web security mistakes.
Example
// A theme manager using localStorage
const ThemeStore = {
get() {
return localStorage.getItem("theme") || "light";
},
set(theme) {
localStorage.setItem("theme", theme);
document.body.dataset.theme = theme;
},
toggle() {
this.set(this.get() === "light" ? "dark" : "light");
}
};
// A multi-step form using sessionStorage for temporary progress
const FormProgress = {
save(step, data) {
sessionStorage.setItem(`form-step-${step}`, JSON.stringify(data));
},
load(step) {
const raw = sessionStorage.getItem(`form-step-${step}`);
return raw ? JSON.parse(raw) : null;
},
clear() {
sessionStorage.clear();
}
};
// On page load, restore the theme
ThemeStore.set(ThemeStore.get());
// Listen for storage changes in other tabs
window.addEventListener("storage", (e) => {
if (e.key === "theme") ThemeStore.set(e.newValue);
});
ThemeStore uses localStorage for a persistent theme that survives reloads. FormProgress uses sessionStorage for temporary form data that clears when the tab closes. The storage event fires in other tabs when localStorage changes, enabling cross-tab theme sync. All data is non-sensitive.
Try it
- JWT Decoder
Decode a JWT to see what data is in it — but never store JWTs in localStorage.
- JSON Formatter
Format JSON data before storing it in localStorage or IndexedDB.
Common mistakes
The mistake
Storing sensitive data like passwords or auth tokens in localStorage.
The fix
localStorage is readable by any JavaScript on the page, including XSS attacks. Store sensitive session data in httpOnly, Secure cookies that JavaScript cannot access. Reserve localStorage for non-sensitive preferences like theme and language.
The mistake
Storing objects directly without JSON.stringify, getting [object Object].
The fix
localStorage only stores strings. Use JSON.stringify(obj) when writing and JSON.parse(str) when reading. Wrap the parse in try/catch because corrupted data will throw.
Related Resources
Related Cheatsheets
- JavaScript Cheatsheet
Reference for localStorage, sessionStorage, and the Storage API.
Practice Web Storage
4 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.