Web Fundamentals

Browser Storage: Cookies, SessionStorage, LocalStorage, IndexedDB

mediumWeb Fundamentals

Browser Storage: Cookies, SessionStorage, LocalStorage, IndexedDB

Learn the interview-ready mental model, practical trade-offs, and production patterns for this web fundamentals topic.

Topic content

TL;DRCookies for auth (httpOnly). sessionStorage for tab-scoped temp data. localStorage for simple persistence. IndexedDB for large/offline structured data. Never store tokens in localStorage.
High Signal
Google
Meta
Netflix
Agoda
Apple
30-Second Answerstart every interview with this

Each browser storage mechanism solves a different problem. Understanding their persistence model, size limits, security risks (especially XSS), performance characteristics, and server accessibility is critical for making correct architectural decisions.

Cookies = a safe the hotel front desk (server) can also open. sessionStorage = a temporary locker in one changing room (tab). localStorage = your personal locker that survives visits. IndexedDB = a large bank vault with organized drawers (indexes) for big or complex belongings.

Choose Storage Based On:
Server Access Needed?
Persistence Required?
Data Size & Structure?
Security Sensitivity?

1Cookies

The only storage automatically sent with every HTTP request to the same domain. Critical for authentication when using httpOnly + Secure + SameSite flags. Limited to ~4KB per domain.

secure-cookie.tsts
res.cookie('sessionId', token, {
  httpOnly: true,
  secure: true,
  sameSite: 'strict',
  maxAge: 1000 * 60 * 60 * 24 * 7 // 7 days
});

2sessionStorage

Per-tab, temporary storage cleared when the tab is closed. Not shared across tabs. Perfect for multi-step wizards, form drafts, or temporary UI state.

3localStorage

Persistent across browser sessions, domain-scoped, synchronous API. Great for user preferences (theme, language) but vulnerable to XSS and blocks the main thread on large operations.

4IndexedDB

A full-featured client-side database with transactions, indexes, and large storage capacity. Asynchronous API. Ideal for offline-first applications, large datasets, and complex querying.

5Security & XSS Risks

All client-side storage (localStorage, sessionStorage, IndexedDB, non-httpOnly cookies) can be read and modified by malicious JavaScript. Always store authentication tokens in httpOnly cookies and enforce strong CSP.

Key Takeaways
  • Cookies are the only storage sent to the server automatically
  • httpOnly + Secure + SameSite cookies are required for authentication
  • localStorage and sessionStorage are synchronous and XSS-vulnerable
  • IndexedDB is the best choice for large or offline-first applications
  • Never store sensitive data in client-side storage
  • Layer storage solutions based on specific requirements
  • Always consider security, performance, and persistence trade-offs