The browser
localStorage
A site's small memory in the browser: strings by key that don't vanish on reload.
Why it exists
JavaScript variables live only while the page is open: reload it, and the chosen theme, a half-written message and a guest's cart are gone. Sending every little thing to a server is slow and not always possible — a guest has no account. localStorage gives a site a small store right in the user's browser: write it, and the data waits for the next visit, even a month later.
Where it's used
- Interface settings: theme, language, font size, a collapsed menu.
- A cart and "favourites" for a guest without an account.
- Drafts: an unfinished comment or form survives an accidentally closed tab.
- Recent searches, "you viewed", recently opened files.
- State libraries: Zustand's
persistand Redux Persist keep part of the state between visits.
Syntax
localStorage.setItem("key", "string");
localStorage.getItem("key"); // a string or null
localStorage.removeItem("key");
localStorage.clear();Examples
const cart = [{ id: 7, qty: 2 }];
localStorage.setItem("shop:cart", JSON.stringify(cart));
// after a page reload:
const saved = JSON.parse(localStorage.getItem("shop:cart") ?? "[]");
console.log(saved[0].qty); // 2// A tiny model of the store: everything becomes a string
const data = {};
const setItem = (key, value) => { data[key] = String(value); };
const getItem = (key) => (key in data ? data[key] : null);
setItem("lives", 9);
getItem("lives"); // → "9"
setItem("toys", ["mouse", "yarn"]);
getItem("toys"); // → "mouse,yarn"
setItem("cat", { name: "Byte" });
getItem("cat"); // → "[object Object]"
getItem("bowl"); // → nullsetItem does with non-strings — and what getItem returns for an empty keyconst saved = JSON.stringify({ theme: "dark" });
const defaults = { theme: "light", sound: true };
({ ...defaults, ...JSON.parse(saved) }); // → { theme: "dark", sound: true }
JSON.parse(null) ?? []; // → [] — no key yetfunction safeParse(text, fallback) {
if (text === null) return fallback;
try {
return JSON.parse(text);
} catch {
return fallback;
}
}
safeParse('["fish"]', []); // → ["fish"]
safeParse(null, []); // → []
safeParse("[object Object]", []); // → []Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
The browser keeps a separate on-disk store for every origin (protocol + domain + port). That site's scripts see all of it; other sites see none of it.
A value is always turned into a string, as with String(value): the number 9 becomes "9", the array [1, 2] becomes "1,2", an object becomes "[object Object]". There's no error — the data is simply lost. That's why structures are saved with JSON.stringify and read with JSON.parse.
For a missing key, getItem returns null. A handy trick: JSON.parse(null) gives null too, so JSON.parse(localStorage.getItem(key)) ?? fallback covers the first visit. It does not protect against corrupted data: JSON.parse throws a SyntaxError on junk, so reading is wrapped in try...catch.
The store is synchronous: getItem and setItem pause JavaScript while they touch the disk. That's why it's small — about 5 MB per origin; when it's full, setItem throws a QuotaExceededError.
sessionStorage works the same way, but lives only until the tab is closed, and each tab has its own.
Traps
How it differs from…
JSON.parse()andJSON.stringify()JSON is the packing format;
localStorageis the place. The store only takes strings, and JSON.stringify and JSON.parse turn objects and arrays into a string and back.try...catchReading from storage is a border with the outside world: the data may have gone bad. try...catch around JSON.parse turns junk into a default value instead of a blank page.
When to pick something else
Don't store secrets (passwords, tokens) or anything you can't afford to lose: the user may clear their data, and private mode wipes it on close. Data needed on another device belongs on the server. For large amounts or files there's the asynchronous IndexedDB, and what should live in one tab only goes in sessionStorage.
Practice
Lessons where this appears
- Memory after a napTale · Chapter 22 · localStorage and JSON
- Why does localStorage only store strings?Why? · Chapter 22 · localStorage and JSON
- Settings that survive a napWorkshop · Chapter 22 · localStorage and JSON
- The Vacuum of OblivionBoss · Chapter 22 · localStorage and JSON
- How a real app is put togetherTale · Chapter 23 · Project: a to-do app
- The Living PageBoss · Chapter 23 · Project: a to-do app