All topics
DOMintermediate

localStorage, sessionStorage, and IndexedDB

The three main client-side storage APIs, ranging from simple synchronous key-value storage to a full asynchronous, transactional database in the browser.

Beyond cookies, browsers offer three progressively more capable client-side storage mechanisms, and choosing among them depends heavily on how much data you need to store, whether it needs structure beyond simple strings, and whether synchronous access is acceptable. Interviewers ask about this trio to see whether you know when a simple key-value store is enough versus when you actually need a real embedded database.

localStorage is like a small notepad in your pocket — quick to jot a note on, but limited in space and only holds plain text. IndexedDB is like an actual filing room with labeled cabinets, folders, and a card-catalog index system for finding files by any attribute, capable of holding vastly more material, but requiring a bit more setup to use properly.

Key Concepts

1
localStorage and sessionStorage share an identical, simple synchronous API (setItem, getItem, removeItem, clear) for storing string key-value pairs, differing only in lifetime — localStorage persists indefinitely until explicitly cleared, sessionStorage clears when its tab closes. Both are limited to roughly 5-10MB per origin (varying by browser) and can only store strings directly, meaning objects must be serialized with JSON.stringify/JSON.parse manually before storing and after retrieving — there's no automatic object support.
localStoragesessionStoragesetItemgetItemremoveItem
2
IndexedDB is a fundamentally different, much more capable tool: a transactional, asynchronous, object-oriented database built into the browser, supporting structured data (including nested objects, Blobs, and Files without manual serialization), indexes for efficient querying by fields other than a primary key, and storage limits typically in the hundreds of megabytes to gigabytes range, tied to available disk space rather than a small fixed cap. Its API is notoriously more verbose and callback/event-based (request.onsuccess, request.onerror) than the other two, though modern wrapper libraries (like idb) make it feel much closer to a Promise-based API.
IndexedDBBlobFilerequest.onsuccessrequest.onerror
3
The practical decision: reach for localStorage/sessionStorage for small amounts of simple key-value data (feature flags, small cached settings, a session-scoped in-progress form), and reach for IndexedDB (often via a wrapper library) when you need to store meaningful amounts of structured data client-side — offline-capable apps, large cached datasets, file/blob storage — where the 5-10MB ceiling and synchronous, string-only nature of Web Storage would be a real limitation.
localStoragesessionStorageIndexedDB