Contents

Web & Networking › How Browsers Work

Browser Storage

Cookies, localStorage, sessionStorage and IndexedDB.

Also known as: web storage, client-side storage, storing data in the browser

Browsers offer several places for a web page to keep data on the user’s device. They differ in size, lifetime, and whether the data is sent to the server.

StorageCapacityLifetimeSent to server?Notes
Cookiessmall (about 4 KB each)until expiry or session endyes, on every matching requestsessions, preferences; can be HttpOnly
localStoragea few MBuntil clearednosimple key-value strings, synchronous
sessionStoragea few MBuntil the tab closesnoper tab
IndexedDBlargeuntil clearednostructured data, asynchronous, can store files
Cache Storagelargeuntil clearednoused by service workers for offline files
localStorage.setItem("theme", "dark");
sessionStorage.setItem("draft", text);
document.cookie;    // cookies are best set by the server with Set-Cookie

Choosing

  • Needs to reach the server (login session): a cookie, with HttpOnly, Secure and SameSite (cookies).
  • Small UI preference that persists: localStorage.
  • Temporary state for one tab: sessionStorage.
  • Lots of structured data, offline apps: IndexedDB (offline-first).

Rules that apply to all

  • It’s per origin, and visible to your own scripts (origin).
  • Treat it as untrusted and temporary. The user (or an extension) can read and edit it, clear it, or the browser can evict it. Quotas and private modes limit it.
  • Don’t store secrets or sensitive personal data, because any injected script can read it (XSS).
  • Wrap access in try/catch, since it can throw.
  • Clear on logout anything tied to the user.
  • Don’t use it as your database. Keep important data on the server.
  • Consider privacy laws for cookies and similar tracking (cookie consent).