localStorage & sessionStorage
The Web Storage API gives every browser tab a simple key–value store built right into the browser — no database, no server, no setup. localStorage persists data across sessions (even after the tab closes), while sessionStorage lives only for the lifetime of a single tab. Together they are the go-to solution for saving user preferences, form drafts, auth tokens, and lightweight app state without any external dependency.
Two Stores, One API
Both storage types share an identical API — the only difference is how long data survives. Understanding when each one gets cleared is the single most important thing to know before you use them:
Storage
interface — setItem, getItem, removeItem,
clear, length, and key(n). Switching between
them is a one-word change.
Storage API at a Glance
Both localStorage and sessionStorage are
pre-built global objects — no constructor, no import needed. Every method works identically on
both:
localStorage.setItem("theme", "dark"); // key, value (both strings)
// ── Read ─────────────────────────────────────────────
const theme = localStorage.getItem("theme"); // → "dark" | null if missing
// ── Delete one key ───────────────────────────────────
localStorage.removeItem("theme");
// ── Delete ALL keys in this origin ───────────────────
localStorage.clear();
// ── Count & enumerate ────────────────────────────────
localStorage.length; // number of stored keys
localStorage.key(0); // key name at index 0
All Storage Methods in Detail
Both stores expose five methods and one property. Here is when and how to use each:
setItem(key, value) — stores a string value
under the given key. Non-string values are auto-coerced to strings
— always JSON.stringify objects.getItem(key) — returns the stored string, or
null if the key doesn't exist. Never returns
undefined.
key(index) — returns the key name at the given
numeric index. Useful for iterating all keys when combined with
length.
removeItem(key) — deletes a single key–value
pair. Silently does nothing if the key does not exist — no error thrown.clear() — removes every
key–value pair from the store for the current origin. Use with caution — it
affects all keys, not just yours.length — a read-only property that gives the
number of stored keys. Combine with key(i) to enumerate all
entries in a loop.// 1. setItem — write
localStorage.setItem("username", "Alice");
localStorage.setItem("score", "42"); // numbers become strings
// 2. getItem — read
const name = localStorage.getItem("username"); // "Alice"
const ghost = localStorage.getItem("nope"); // null
// 3. key(n) — enumerate
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i);
console.log(k, localStorage.getItem(k));
}
// 4. removeItem — delete one key
localStorage.removeItem("score"); // gone
// 5. clear — wipe everything for this origin
localStorage.clear(); // all keys removed
Storing Objects with JSON
Web Storage only stores strings. Trying to save an object
directly stores the useless "[object Object]" string. Always use
JSON.stringify to write and JSON.parse to read back objects:
// ❌ WRONG — object gets coerced to "[object Object]"
localStorage.setItem("user", { name: "Alice", age: 30 });
localStorage.getItem("user"); // → "[object Object]" 💥
// ✅ RIGHT — serialize with JSON.stringify, deserialize with JSON.parse
localStorage.setItem("user", JSON.stringify({ name: "Alice", age: 30 }));
const user = JSON.parse(localStorage.getItem("user"));
console.log(user.name); // "Alice" ✅
// A reusable helper that handles JSON + missing key + parse errors
function readStorage(key, fallback = null) {
try {
const raw = localStorage.getItem(key);
return raw !== null ? JSON.parse(raw) : fallback;
} catch {
return fallback;
}
}
function writeStorage(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch (e) {
console.warn("Storage full or disabled", e);
}
}
// Usage
writeStorage("cart", [{ id: 1, qty: 2 }, { id: 4, qty: 1 }]);
const cart = readStorage("cart", []); // [] if missing
localStorage vs sessionStorage — Full Comparison
Picking the right store is simple once you understand each dimension. Here's a complete side-by-side breakdown:
| Feature | localStorage | sessionStorage |
|---|---|---|
| Persistence | Until cleared — survives restarts | Tab lifetime — gone on tab close |
| Scope | All tabs of the same origin | Single tab only — isolated per tab |
| Shared across tabs | Yes | No |
| Storage limit | ~5 MB (browser-specific) | ~5 MB (browser-specific) |
| Value type | String only (use JSON for objects) | String only (use JSON for objects) |
| Sent to server | Never | Never |
| Accessible from JS | Yes — synchronous | Yes — synchronous |
| Private browsing | Cleared when private session ends | Cleared when tab closes |
| Best for | Theme, preferences, auth tokens | Wizard steps, form drafts, one-time state |
The storage Event — Cross-Tab Sync
When localStorage changes in one tab, every other tab on
the same origin receives a storage event — a built-in cross-tab communication
channel. Note that the tab that made the change does not fire the event on itself:
// Tab A — makes a change
localStorage.setItem("theme", "light");
// Tab B — listens for that change (fires in OTHER tabs only)
window.addEventListener("storage", (e) => {
console.log(e.key); // "theme"
console.log(e.oldValue); // "dark" (previous value)
console.log(e.newValue); // "light" (new value)
console.log(e.storageArea); // the localStorage object
console.log(e.url); // URL of the tab that changed it
if (e.key === "theme") {
document.documentElement.setAttribute("data-theme", e.newValue);
}
});
storage event is only emitted for localStorage changes.
sessionStorage is isolated per tab, so there is no other tab to notify.
Key Method Reference
A bookmark-ready reference for every property and method on the
Storage interface:
value as a string under key.
If the key already exists it is overwritten silently. Throws a
QuotaExceededError (DOMException) if the storage quota is full — always
wrap writes in try/catch for production code.
null if the
key does not exist. Never returns undefined. Remember to
JSON.parse if you stored an object.
key. If the key
does not exist the call is silently ignored — no error thrown. Safe to call
speculatively.removeItem with a prefix pattern instead for safer cleanup.key(i).index, or
null if out of range. Key order is browser-defined — do not rely on
insertion order.
key, oldValue,
newValue, url, storageArea. Does not fire for
sessionStorage changes.
Real-World Use Cases
Here are the patterns you will encounter Web Storage used for in real projects:
<head> script to avoid flash of wrong theme on
page load.storage event to keep all open
tabs consistent.Common Patterns
Three patterns you'll use in almost every real project that touches browser storage:
// In <head> — runs before paint to avoid flash of wrong theme
(function () {
const saved = localStorage.getItem("theme");
const preferred = window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark" : "light";
document.documentElement.setAttribute("data-theme", saved || preferred);
})();
// Toggle button handler
function toggleTheme() {
const next = document.documentElement.getAttribute("data-theme") === "dark"
? "light" : "dark";
document.documentElement.setAttribute("data-theme", next);
localStorage.setItem("theme", next);
}
// Autosave every text field in a form — survives accidental refresh
const FORM_KEY = "contact-draft";
function saveDraft() {
const form = document.getElementById("contactForm");
const data = {};
[...form.elements].forEach(el => {
if (el.name) data[el.name] = el.value;
});
sessionStorage.setItem(FORM_KEY, JSON.stringify(data));
}
function restoreDraft() {
const raw = sessionStorage.getItem(FORM_KEY);
if (!raw) return;
const data = JSON.parse(raw);
const form = document.getElementById("contactForm");
Object.entries(data).forEach(([k, v]) => {
if (form.elements[k]) form.elements[k].value = v;
});
}
// Debounced autosave + restore on load
document.getElementById("contactForm")?.addEventListener("input", () => {
clearTimeout(window._draftTimer);
window._draftTimer = setTimeout(saveDraft, 600);
});
document.addEventListener("DOMContentLoaded", restoreDraft);
// Prefix all keys to avoid collisions with third-party scripts
function createStore(prefix, storage = localStorage) {
const pre = k => `${prefix}:${k}`;
return {
get: (k, fb = null) => {
try {
const v = storage.getItem(pre(k));
return v !== null ? JSON.parse(v) : fb;
} catch { return fb; }
},
set: (k, v) => { try { storage.setItem(pre(k), JSON.stringify(v)); } catch {} },
del: (k) => storage.removeItem(pre(k)),
clear: () => {
for (let i = storage.length - 1; i >= 0; i--) {
const k = storage.key(i);
if (k?.startsWith(prefix + ":")) storage.removeItem(k);
}
}
};
}
const appStore = createStore("myapp");
appStore.set("theme", "dark"); // stores "myapp:theme"
appStore.get("theme", "light"); // "dark"
appStore.clear(); // only clears "myapp:*" keys
localStorage. The user closes
the browser and reopens it the next day. What happens to the cart data?localStorage.setItem("count", 5). What does
localStorage.getItem("count") return, and what is its type?
- The Web Storage API provides two synchronous key–value stores:
localStorage(persists forever) andsessionStorage(lives for one tab session). - Both share the same five-method interface:
setItem,getItem,removeItem,clear, andkey(n), plus thelengthproperty. - Storage only holds strings. Always
JSON.stringifyobjects before writing andJSON.parseafter reading — and wrap in try/catch to handle parse errors gracefully. - localStorage is shared across all tabs of the same origin. sessionStorage is isolated per tab — two tabs cannot read each other's session data.
- The
storageevent fires in other tabs when localStorage changes — a free cross-tab communication channel. It does not fire for sessionStorage. - Both stores have a limit of approximately 5 MB per origin. Exceeding
it throws a
QuotaExceededError— always wrap writes in try/catch in production. - Never store sensitive data in Web Storage — it is accessible to any JavaScript on the page. Use HttpOnly cookies for auth tokens in high-security applications.
- Common patterns: theme persistence, shopping cart, form autosave (sessionStorage), multi-step wizard, and namespaced storage wrappers to avoid key collisions.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.