foundation
Web Storage
Compare localStorage and sessionStorage, synchronous costs, quotas, serialization, lifetime, and storage events.
localStorage and sessionStorage store string data per origin with simple synchronous APIs. localStorage persists across sessions; sessionStorage is scoped to a top-level browsing session. They are convenient for small non-sensitive preferences but unsuitable for large data, high-frequency writes, or secrets exposed to XSS.
const key = 'theme';
localStorage.setItem(key, JSON.stringify({ mode: 'dark' }));
const theme = JSON.parse(localStorage.getItem(key) ?? '{"mode":"light"}');
The storage event fires in other documents from the same origin when localStorage changes — useful for cross-tab theme sync, not a durable message bus.
On interviews: compare Web Storage with cookies, IndexedDB, memory, and server state by sensitivity and lifetime.
Common pitfalls: synchronous reads can block the main thread. Storing tokens in Web Storage makes XSS consequences worse.
The trade-off is convenience versus control — pick the mechanism that matches your coupling and performance budget.
Checklist:
- Store only small, non-secret data.
- Serialize with explicit schema/version.
- Avoid high-frequency writes on input events.
- Know lifetime: local vs session.