Web storage: localStorage, sessionStorage and IndexedDB
In short: Browsers can store data locally on the user’s device: simple key-value pairs (localStorage, sessionStorage) or a real database (IndexedDB).
In more detail: Besides cookies, browsers offer several ways to store data on the device, for example settings, drafts or offline data. They are bound to the origin (scheme, domain, port): another site cannot read them.
In Depth
localStorage and sessionStorage
Simple key-value stores for text, about 5 MB per origin:
localStorage.setItem('theme', 'dark');
const t = localStorage.getItem('theme');
localStorage.removeItem('theme');- localStorage: persists permanently, even after closing the browser.
- sessionStorage: only for the tab, ends with it.
Accesses are synchronous and block the main thread, so not for large data. Objects must be stored as
JSON.stringify. Both can fail if the user blocks storage or browses in a private window: wrap accesses intry/catch.
IndexedDB
A real database in the browser for structured, also large data (hundreds of MB and more), with indexes, transactions and binary data such as files and images. The programming interface is asynchronous and event-based, so a helper library (idb, Dexie) is usually used. IndexedDB is the basis for offline apps (PWA) together with the service worker.
Compared with cookies
Cookies are sent with every request to the server (up to about 4 KB), whereas web storage stays local. For sign-ins, cookies with HttpOnly and Secure are better because JavaScript cannot read them: a sign-in token in localStorage can be stolen by an XSS vulnerability.
Privacy and practice
Local storage too can trigger a consent requirement if it is not strictly necessary (TDDDG). Do not store secrets or sensitive data in plain text. The browser can delete storage when space runs low; navigator.storage.persist() asks for permanent storage. For synchronisation across devices you need a server.
See also: Cookies, XSS, Service worker, Offline-first and background sync