Tech Interview RoomStudy guides

Browser & Performance

Compare browser storage options: cookies, localStorage, sessionStorage, IndexedDB and the Cache API.

Intermediate · 2 min read · Lesson 4 of 8 in Browser & Performance

Cookies

  • About 4 KB each; sent with every request to their domain (adds weight to every request).
  • Can be HttpOnly (hidden from JavaScript), Secure, SameSite, with expiry.
  • Use for: session identifiers and server-read preferences.

localStorage

  • About 5 MB per origin; synchronous string key/value API; persists until cleared.
  • Shared across tabs of the same origin; the storage event notifies other tabs of changes.
  • Readable by any script on the page, so never store secrets there. Synchronous access blocks the main thread for big values.
  • Use for: UI preferences, drafts, small caches.

sessionStorage

  • Same API, but scoped to one tab and cleared when it closes.
  • Use for: per-tab wizard state, scroll restoration.

IndexedDB

  • Asynchronous, transactional database for large structured data (hundreds of MB, depending on disk quota), including blobs and files; works in Web Workers.
  • The raw API is verbose; use idb or Dexie.
  • Use for: offline data, large caches, local-first apps.

Cache API

  • Stores Request → Response pairs; used by service workers to serve assets and API responses offline (PWAs).

Other notes

navigator.storage.estimate() reports usage; navigator.storage.persist() asks the browser not to evict data. Safari may delete script-writable storage after 7 days without user interaction for some sites.

Example

js
// Preferences: small and non-sensitive
localStorage.setItem('theme', 'dark');

// Sync logout across tabs
window.addEventListener('storage', e => {
  if (e.key === 'logout') window.location.assign('/login');
});

// Large offline data with the idb wrapper
import { openDB } from 'idb';
const db = await openDB('app', 1, {
  upgrade(db) { db.createObjectStore('notes', { keyPath: 'id' }); },
});
await db.put('notes', { id: 'n1', text: 'Offline note', updated: Date.now() });
const all = await db.getAll('notes');

Follow-up questions interviewers ask

Try answering each one before you open it.

How would you share state between tabs?

The storage event (localStorage changes), BroadcastChannel (send any structured message to all same-origin tabs), a SharedWorker, or the Web Locks API to elect one leader tab, for example to keep a single WebSocket connection.