Persist Data Across Page Loads
JavaScript Local Storage
`localStorage` is a tiny string-keyed key/value store, scoped to your origin and surviving page reloads.
What you'll learn
- Read and write strings to `localStorage`
- Store objects via `JSON.stringify`
- Know the difference vs `sessionStorage` and cookies
localStorage is a string-to-string key/value store the browser
keeps per origin (scheme + domain + port). It survives reloads,
tab closes, and reboots. It’s synchronous and roughly 5 MB.
The API
localStorage.setItem("theme", "dark");
console.log(localStorage.getItem("theme")); // "dark"
console.log(localStorage.getItem("missing")); // null
localStorage.removeItem("theme");
// localStorage.clear(); // wipe everything for this origin ▶ Preview: console
getItem returns null for missing keys, never undefined.
Everything Becomes a String
localStorage.setItem("count", 3);
console.log(localStorage.getItem("count")); // "3" ← string!
console.log(typeof localStorage.getItem("count")); // "string"
localStorage.setItem("on", true);
console.log(localStorage.getItem("on") === "true"); // true ▶ Preview: console
Storing Objects — Use JSON
const user = { id: 1, name: "Ada" };
localStorage.setItem("user", JSON.stringify(user));
const back = JSON.parse(localStorage.getItem("user"));
console.log(back.name); // "Ada" ▶ Preview: console
This is the standard pattern. Wrap reads in try/catch if the
data might have been written by older code in a different shape.
A Tiny Helper
const store = {
get(key, fallback = null) {
const raw = localStorage.getItem(key);
if (raw === null) return fallback;
try { return JSON.parse(raw); } catch { return fallback; }
},
set(key, value) {
localStorage.setItem(key, JSON.stringify(value));
},
remove(key) { localStorage.removeItem(key); },
};
store.set("user", { id: 1, name: "Ada" });
console.log(store.get("user")); // { id: 1, name: "Ada" } sessionStorage Is the Same API, Different Lifetime
| Storage | Survives reload? | Survives tab close? | Visible to other tabs? |
|---|---|---|---|
localStorage | yes | yes | yes (same origin) |
sessionStorage | yes | no | no — current tab only |
| Cookie | until expiry | until expiry | sent to server on every request |
If you don’t want the data to outlive the tab, use sessionStorage.
Things to Watch Out For
- Synchronous I/O. Each read/write blocks the main thread. Don’t store huge blobs here.
- Quota. Browsers cap origins at ~5 MB.
setItemthrows if you exceed it. - JSON edge cases.
Dates become strings;undefined, functions, andBigIntdon’t survive. (See the JSON lesson.) - Don’t put secrets here. Anything in
localStorageis readable by any JavaScript running on your page — including XSS attackers.
Up Next
A more powerful pattern: searching, validating, and rewriting text with regular expressions.
JavaScript Regex →