Full answer
Options and their roles:
- Cookies: small (about 4 KB each), sent with every matching request, can be
HttpOnly. Use them for sessions and server-visible state. - localStorage: string key-value pairs, synchronous, persists until cleared, shared by tabs of one origin. The usual limit is a few megabytes per origin, but it differs between browsers. Fine for a theme or a language choice.
- sessionStorage: the same API, but limited to one tab and removed when it closes.
- IndexedDB: a transactional object database. It stores structured-cloned values (objects, arrays, Blobs, typed arrays), supports indexes and range queries, and is asynchronous, so it does not block the main thread. It is available in workers.
- Cache API: stores Request and Response pairs, used by service workers.
Why choose IndexedDB over localStorage:
- Large data, such as downloaded lessons, drafts, or a local copy of a list for offline use. Quotas are usually much larger, but they depend on the disk space and the browser.
- Structured data and queries, without turning everything into JSON strings.
- Non-blocking access.
localStorage.getItemblocks the main thread, so many reads on a hot path can hurt responsiveness. - Access from a worker, and transactions that keep related writes consistent.
Costs: the raw API is event-based and verbose, so teams wrap it in promises or use a small library. Schema changes need version upgrades in onupgradeneeded.
Rules for any storage:
- Storage is per origin, and a user can clear it, so treat it as a cache that can disappear. Browsers can also evict data under storage pressure unless the site asks for persistence with
navigator.storage.persist(). - Do not store secrets or session tokens where scripts can read them.
- Plan a migration for changes in the data format, and handle private browsing modes and quota errors.
The page below opens a database, writes an object, reads it back and shows that localStorage turns a number into a string.
html
<script type="module">
const open = () => new Promise((resolve, reject) => {
const req = indexedDB.open('schoolabe', 1);
req.onupgradeneeded = () => req.result.createObjectStore('notes', { keyPath: 'id' });
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
const wrap = (req) => new Promise((resolve, reject) => {
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
const store = (db, mode) => db.transaction('notes', mode).objectStore('notes');
const db = await open();
await wrap(store(db, 'readwrite').put({ id: 1, text: 'Lesson 3 notes', tags: ['css'] }));
const note = await wrap(store(db, 'readonly').get(1));
localStorage.setItem('count', 42);
window.out = { text: note.text, tags: note.tags, local: typeof localStorage.getItem('count') };
</script>Run in headless Chrome 156 through Playwright. Two full runs gave the same results. Checked in headless Chrome on a test origin. Quota, eviction, private browsing and other browsers were not tested.
Key points
- Cookies are for server-visible state. localStorage is small, sync strings.
- sessionStorage is per tab. Cache API stores responses.
- IndexedDB stores structured objects asynchronously, with indexes and transactions.
- Choose IndexedDB for large, structured or offline data.
- Storage can be cleared, so treat it as a cache and keep secrets out.
Common mistakes
- Storing tokens or personal data in localStorage.
- Storing large JSON in localStorage and blocking the main thread.
- Assuming the data will always be there.
- Changing the stored shape without a version upgrade.
Follow-ups
- What does navigator.storage.persist do?
- How does a version upgrade work in IndexedDB?
- Why is localStorage unavailable in a worker?
Tips
- Describe each storage type in a line, then give the decision rule.
- Mention eviction and quota to show you know the limits.