Web storage
Overview
The browser can remember small amounts of data for your site, even after the page is closed. This is how this course remembers which topics you’ve completed — and how many sites remember your theme, a half-written draft, or the last tab you had open.
localStorage.setItem('lastLesson', 'arrow-functions');
localStorage.getItem('lastLesson'); // 'arrow-functions'
localStorage.removeItem('lastLesson');
localStorage.clear(); // everything for this sitegetItem returns null for a key that doesn’t exist, which pairs nicely with ?? for defaults:
const fontSize = Number(localStorage.getItem('fontSize') ?? 16);localStorage vs sessionStorage
localStorage |
sessionStorage |
|
|---|---|---|
| Lasts until | cleared by code or the user | the tab is closed |
| Shared between tabs | yes | no |
| Good for | preferences, progress, drafts | one visit’s state, multi-step forms |
Both have exactly the same methods: setItem, getItem, removeItem, clear, key(i) and length.
Storage belongs to an origin — the protocol, domain and port. https://academy.example.com can’t read the storage of https://other.example.com. It also belongs to one browser on one device: progress saved on a laptop isn’t on a phone. For that, you need a server and accounts.
Storing objects
Storage only holds strings, so convert objects with JSON:
const progress = { done: ['loops', 'arrays'], updated: Date.now() };
localStorage.setItem('progress', JSON.stringify(progress));
const saved = JSON.parse(localStorage.getItem('progress') ?? '{}');Numbers and booleans become strings too: setItem('count', 5) stores '5', and setItem('dark', false) stores 'false' — which is truthy! Convert when reading.
A safe little wrapper
Stored data can be missing, written by an older version of your app, or edited by hand in DevTools. Wrapping storage once protects every caller:
const store = {
get(key, fallback) {
try {
const raw = localStorage.getItem(key);
return raw === null ? fallback : JSON.parse(raw);
} catch {
return fallback; // blocked storage or broken JSON
}
},
set(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
// full, or blocked (some private modes) — not worth crashing over
}
},
};
const done = store.get('done', []);
store.set('done', [...done, 'web-storage']);Versioning keys
If the shape of your saved data changes, old saved data won’t fit. Prefixing keys with your app name and a version keeps things tidy: academy:v2:progress. When you change the format, bump the version and ignore (or migrate) the old key.
Reacting to changes in other tabs
When one tab changes localStorage, every other tab of the same site receives a storage event. Use it to keep tabs in sync:
window.addEventListener('storage', (event) => {
if (event.key === 'theme') {
document.documentElement.dataset.theme = event.newValue;
}
});Things to know
- Space is limited (about 5 MB per site).
- Reading and writing is synchronous, so keep the data small.
- Private browsing and some settings block storage — wrap calls in
try…catch. - Users can clear it at any time, so treat it as a convenience, never the only copy of something important.
- DevTools → Application (Chrome/Edge) or Storage (Firefox) shows and lets you edit everything stored.
Not for secrets. Any script on your page can read web storage, so never keep passwords or tokens there.
Other ways to store data
| Option | Use it for |
|---|---|
localStorage / sessionStorage |
small strings: settings, progress, drafts |
| Cookies | small values the server needs to see on every request (sessions) |
| IndexedDB | large or structured data, files, offline apps |
| Cache API | saved network responses for offline use |
For most beginner projects, localStorage is all you need.
Remember the theme
Save the chosen theme when the toggle is clicked, and apply the saved theme when the page loads. If nothing is saved, follow the system setting (prefers-color-scheme).
const toggle = document.querySelector('#theme-toggle');const toggle = document.querySelector('#theme-toggle');
const systemDark = matchMedia('(prefers-color-scheme: dark)').matches;
document.documentElement.dataset.theme =
localStorage.getItem('theme') ?? (systemDark ? 'dark' : 'light');
toggle.addEventListener('click', () => {
const next = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
document.documentElement.dataset.theme = next;
localStorage.setItem('theme', next);
});Summary
localStoragekeeps data until it’s cleared;sessionStorageuntil the tab closes.- Storage is per site (origin) and per browser — it doesn’t follow the user to another device.
- Values are always strings — use JSON for objects, and handle missing or broken data.
- The
storageevent tells other tabs whenlocalStoragechanges. - Never store passwords or other secrets in web storage.