The previous lesson in this module explained how import and export split your program into separate files. This lesson stays inside the browser and looks at the place where a browser keeps small pieces of data for you between page loads. The next lesson in this module leaves the browser's own storage behind and asks a server for real data over the network.
The previous lesson in this module covered "import and export: ES Modules in the Browser", and the next lesson in this module is about "fetch() and HTTP Requests Without Libraries".
localStorage and sessionStorage are the two Web Storage areas that every browser ships with. localStorage keeps a small amount of data for each site until you clear it, and sessionStorage keeps it only for the lifetime of one tab. Both of them are synchronous, they hold strings only, and both of them are easy to misuse, so this lesson shows how to wrap them properly, when each one is the right choice, and how to survive the failure cases that crash a page quietly.
What is localStorage and what belongs in it?
Think of localStorage as a small key-and-value shelf that is attached to your site. A value written under https://example.com can be read by every page on that origin, and it survives a browser restart. It is ideal for small preferences, such as a chosen theme, a saved shipping address, the last tab you were on, or a draft that you want to survive an accidental refresh.
It is not a database. The API is synchronous, so every read and every write blocks the main thread for the moment that it takes, and the total space for one origin is usually only a few megabytes. Storing a long list of records here will eventually fail, and when it fails your page has to cope with that.
Why does localStorage only accept strings?
Every value is turned into a string on the way in and handed back as a string on the way out. Numbers, booleans, objects, and arrays all arrive as text, and that quietly changes their type.
localStorage.setItem('theme', 'dark');
localStorage.setItem('rows', 25);
console.log(localStorage.getItem('theme')); // 'dark'
console.log(localStorage.getItem('rows')); // 25 (a string, not a number)
console.log(localStorage.getItem('missing')); // null (absent keys give null)
console.log(localStorage.length); // 2
localStorage.removeItem('theme');
localStorage.clear();
Storing an object directly is worse than it looks. The browser converts it with its own string conversion, so you get [object Object] back and no warning that anything was lost.
How do you store objects without corrupting them?
Serialise with JSON.stringify on the way in and parse with JSON.parse on the way out. Wrapping that in one small adapter keeps the rest of your code from having to remember the rule, and it gives you a single place to handle parse failures.
// storage.js
export function createStore(backing, prefix) {
const fullKey = function (name) {
return prefix + name;
};
return {
get(name, fallback) {
const raw = backing.getItem(fullKey(name));
if (raw === null) {
return fallback === undefined ? null : fallback;
}
try {
return JSON.parse(raw);
} catch (error) {
return fallback === undefined ? null : fallback;
}
},
set(name, value) {
backing.setItem(fullKey(name), JSON.stringify(value));
},
remove(name) {
backing.removeItem(fullKey(name));
},
keys() {
const names = [];
for (let index = 0; index < backing.length; index += 1) {
const key = backing.key(index);
if (key !== null && key.startsWith(prefix)) {
names.push(key.slice(prefix.length));
}
}
return names;
},
};
}
The adapter takes the storage area as an argument on purpose, so that the same code can serve both areas and a test can pass in a plain object instead of touching the browser at all. The keys() method walks the area by position rather than trusting an object listing, because a storage area is a special object whose properties are not ordinary own properties.
// app.js
import { createStore } from './storage.js';
const prefs = createStore(localStorage, 'prefs:');
const draft = createStore(sessionStorage, 'draft:');
prefs.set('theme', 'dark');
prefs.set('density', { rows: 25, compact: false });
console.log(prefs.get('theme')); // dark
console.log(prefs.get('density')); // { rows: 25, compact: false }
console.log(prefs.get('missing')); // null
const names = prefs.keys();
names.sort();
console.log(names); // [ 'density', 'theme' ]
draft.set('reply', 'hello');
console.log(draft.get('reply')); // hello
| Method | Returns | Use it for |
|---|---|---|
setItem(key, value) | nothing | Writing; the value is stringified |
getItem(key) | string or null | Reading one key |
removeItem(key) | nothing | Deleting one key |
clear() | nothing | Wiping every key for the origin |
key(index) | string or null | Reading the key at a given position |
length | number | How many keys are stored |
When should you reach for sessionStorage instead?
The two areas share one API and differ in their lifetime, their scope, and what happens when a tab is duplicated.
| localStorage | sessionStorage | |
|---|---|---|
| Lifetime | Until you or the user clear it | Until that tab is closed |
| Sharing | Shared by every tab on the origin | Private to one tab |
| Duplicating a tab | The copy reads the same data | The copy starts with its own empty copy |
| Typical use | Theme, locale, remembered user, cart | Unsaved form text, wizard step, one-off state |
The duplication difference is worth remembering. If a user duplicates a tab that holds an unsaved draft in sessionStorage, then the copy has nothing, which is usually what you want for a draft. If the draft lived in localStorage, both tabs would write to the same key, and the second save would overwrite the first one.
What happens when the quota runs out or storage is blocked?
Two failures matter here. The first one is a full quota, where writing throws an error with the name QuotaExceededError. The second one is storage being unavailable altogether, which some privacy modes and enterprise policies cause. If you let either one escape, the rest of your handler never runs and the user sees a dead button with no explanation at all.
// safe-set.js
export function safeSet(backing, key, value) {
try {
backing.setItem(key, JSON.stringify(value));
return { ok: true };
} catch (error) {
if (error.name === 'QuotaExceededError' || error.code === 22) {
return { ok: false, reason: 'storage-full' };
}
return { ok: false, reason: error.name };
}
}
// A stand-in that behaves like a storage area with no space left.
const fullQuota = {
setItem() {
const error = new Error('out of space');
error.name = 'QuotaExceededError';
throw error;
},
};
console.log(safeSet(fullQuota, 'k', { a: 1 }));
// { ok: false, reason: 'storage-full' }
Returning a result object instead of letting the exception fly means that the caller decides what to do. It can show a message, drop the oldest entry, or carry on without saving anything. Because the function receives the storage area as an argument, the failure path can be tested without filling up a real browser. The stand-in in the snippet throws the same error that a full quota produces, and the function reports storage-full without crashing.
How do two open tabs of the same app stay in sync?
A change in one tab does not fire an event in the tab that made it. It does fire in every other tab on the origin, through the storage event. That event carries the key, the old value, and the new value, which is everything you need to refresh a view.
// storage-events.js
export function describeStorageChange(event) {
if (event.key === null) {
return 'storage cleared in another tab';
}
if (event.newValue === null) {
return 'removed: ' + event.key;
}
return 'changed: ' + event.key + ' = ' + event.newValue;
}
// app.js
import { describeStorageChange } from './storage-events.js';
window.addEventListener('storage', function (event) {
console.log(describeStorageChange(event));
});
There is one subtlety worth remembering. The event never fires in the tab that performed the write. If you rely on it to re-render something, then update your own view at the same time as you write, or route both paths through one function.
What to remember about Web Storage
- Both areas store strings only, so serialise objects with
JSON.stringifyand parse them back withJSON.parse. - Wrap the raw API in a small adapter, so that parse failures and key prefixes are handled in one place.
- Use
localStoragefor preferences that should outlive the tab, andsessionStoragefor drafts that should not. - Guard every write, because a full quota throws
QuotaExceededErrorand a blocked storage area throws on the first access. - The
storageevent syncs the other tabs and never the tab that made the change.
Try it yourself: Open your browser console on any page and run the first block. Then save an object with localStorage.setItem('user', { id: 7 }) and read it back, and you will get the string [object Object], which is the exact mistake that the adapter exists to prevent. Finally, put a page on localhost, open it in two tabs, change localStorage in one of them, and watch the storage event fire in the other one.