Simple key-value storage in the browser
The Web Storage API gives every origin two synchronous string key-value stores —
localStorage and sessionStorage — sharing the same Storage interface but
differing in lifetime and scope. This reference lists the methods and the length
property, the StorageEvent fired on cross-tab changes, and the quota limits that
trip up real apps.
How it works
Both areas expose the same handful of methods, and all values are strings:
localStorage.setItem("theme", JSON.stringify({ dark: true }));
const raw = localStorage.getItem("theme");
let theme = { dark: false };
try {
const parsed = raw ? JSON.parse(raw) : null;
if (parsed && typeof parsed.dark === "boolean") theme = parsed;
} catch {
/* corrupt value — fall back to default */
}
window.addEventListener("storage", (e) => {
if (e.key === "theme") applyTheme(e.newValue);
});
Writes are synchronous and can block the main thread, so keep payloads small.
When you exceed the per-origin quota the call throws QuotaExceededError. The
storage event lets other tabs of the same origin react to changes, but it never
fires in the tab that wrote the value.
Tips and notes
- Store strings only; serialise with
JSON.stringifyand validate the shape afterJSON.parse. - Wrap writes in
try/catch— private-browsing modes and full quotas both throw. lengthandkey(i)let you enumerate entries, but order is not guaranteed across browsers.- Use
sessionStoragefor per-tab, throwaway state andlocalStoragefor data that should survive a reload.