Lesson 18 of 28
In progress
Saving data with localStorage
Store small values in the browser, serialise objects safely, and know when storage is the wrong tool.
localStorage keeps key-value strings in the browser, survives a reload and has no server involved. It is perfect for a theme choice or a small task list, and wrong for anything sensitive or large.
What you will learn
- Write and read strings, and serialise objects with JSON.
- Handle quota errors and corrupted data.
- Decide between local storage, session storage and a server.
The API is four methods
Editable. Runs in your browser.
localStorage.removeItem("theme");
console.log(localStorage.getItem("theme"));
localStorage.clear();
Press Run to see the output.
getItem returns null for a missing key, not undefined. Everything is stored as a string, so setItem("count", 3) stores "3", and reading it back gives a string.
Keys are shared across the whole origin, so prefix them: tin.theme, tin.tasks. A generic key such as data will collide with another script on the same site.
Objects need JSON
Editable. Runs in your browser.
localStorage.setItem("tin.tasks", JSON.stringify(tasks));
const raw = localStorage.getItem("tin.tasks");
const restored = raw ? JSON.parse(raw) : [];
console.log(restored.length);
Press Run to see the output.
Storing an object directly produces "[object Object]", which cannot be parsed back. Always stringify on the way in.
Reading needs the same care in reverse: the key may be absent, and the stored text may be corrupted. A small helper keeps both concerns in one place.
Editable. Runs in your browser.
try {
return JSON.parse(raw);
} catch (error) {
console.warn("Discarding bad data for", key);
return fallback;
}
}
console.log(readJSON("tin.missing", []));
Press Run to see the output.
When writes fail
Storage can throw. Private browsing modes, disabled storage and a full quota all produce exceptions, and an unhandled one breaks the feature that triggered the write.
Editable. Runs in your browser.
console.log(save("tin.settings", { theme: "dark" }));
Press Run to see the output.
The usual cause is QuotaExceededError, which means the origin has hit its limit, typically around 5 MB. Handle it by telling the user that changes will not persist, rather than pretending the save worked.
Storage is per origin, not per person
Anything in localStorage is readable by any script on the same origin and remains after logout. Never store tokens, passwords, personal records or anything you would not put in a public cache.
It is also visible in DevTools and copyable, so treat it as user-editable. Validate it the same way you would validate a network response.
For data that must follow a person across devices, the server is the only option. Local storage is a convenience for this browser, not a database. It is also unencrypted, so any extension or person with access to the machine can read it: fine for a theme choice, not fine for a home address.
Changes in another tab
The storage event fires in other tabs of the same origin when a value changes. It does not fire in the tab that made the change, which is worth remembering when testing.
Editable. Runs in your browser.
Press Run to see the output.
sessionStorage and cookies
sessionStorage has the same API and is cleared when the tab closes, which suits a draft or a one-time flow.
Cookies are sent to the server with every request, so they are the right place for a session identifier, and the wrong place for bulk data. HttpOnly cookies cannot be read by JavaScript, which is a security feature.
Editable. Runs in your browser.
Press Run to see the output.
A theme preference, end to end
Editable. Runs in your browser.
function applyTheme(theme) {
document.documentElement.dataset.theme = theme;
localStorage.setItem(KEY, theme);
}
const saved = readJSON(KEY, null) ?? "light";
applyTheme(saved === "dark" ? "dark" : "light");
console.log(document.documentElement.dataset.theme);
Press Run to see the output.
The stored value is untrusted, so the code maps it to one of two known values instead of assigning it directly to the attribute. That small check prevents an unexpected theme name from breaking the stylesheet.
Calling JSON.parse(localStorage.getItem("x")) without a guard throws on the first visit, when the key is missing and getItem returns null. JSON.parse(null) returns null rather than throwing, but a corrupted string throws, so the helper with a fallback is still the right pattern.
Write saveTasks(tasks) and loadTasks() using one key, JSON, and a fallback to an empty array. Test loading before anything has been saved, then save two tasks and load them back.
Show solution
Editable. Runs in your browser.
function saveTasks(tasks) {
try {
localStorage.setItem(KEY, JSON.stringify(tasks));
return true;
} catch (error) {
console.warn("save failed", error.name);
return false;
}
}
function loadTasks() {
const raw = localStorage.getItem(KEY);
if (!raw) return [];
try {
const value = JSON.parse(raw);
return Array.isArray(value) ? value : [];
} catch (error) {
return [];
}
}
console.log(loadTasks());
saveTasks([{ id: 1, title: "Read" }, { id: 2, title: "Build" }]);
console.log(loadTasks().length);
Press Run to see the output.
The array check matters: valid JSON can still be the wrong shape, and returning an array keeps every caller from adding its own guard.
Recap
- Storage holds strings per origin; stringify objects and prefix keys.
- Guard both missing keys and corrupted JSON, and expect writes to fail.
- Never store secrets; use the server for data that must follow the user.
You have finished data and asynchronous JavaScript. Next, you will use the modern syntax that makes this code shorter and clearer.
How much can localStorage hold?
Is localStorage synchronous?
Progress is saved in this browser only. No account, no email.