Back
Web Fundamentals

Browser Storage: Cookies, SessionStorage, LocalStorage, IndexedDB

Web Fundamentals
Build & Deployment: Monorepo, CI/CD, Strategies & Release SafetyState Management: Choosing the Right SolutionRedux: Predictable State Container (RTK + RTK Query)React Query (TanStack Query): Server State CachingData Fetching Patterns: REST, GraphQL, tRPC & Real-timeGraphQL Fundamentals for Frontend: Shape, Caching, and TradeoffsgRPC-Web Fundamentals: Browser Constraints and Proxy ModelCaching Strategies: Client, Server & EdgeData Normalization: Organizing State for PerformanceAPI Design Best Practices: Pagination, Errors, Versioning & Type SafetyAPI Versioning Strategies for Frontend CompatibilityPagination: Offset vs Cursor-BasedRate Limiting & API Resilience: Retries, Backoff, Jitter, IdempotencyHow Frontend Developers Can Handle Millions of API Requests Without Crashing EverythingBrowser Storage: Cookies, SessionStorage, LocalStorage, IndexedDBReal-time Communication: WebSockets, SSE & PollingWebRTC: Real-Time Communication in the BrowserCore Web Vitals: LCP, INP & CLSPerformance Optimization Trade-offsCritical Resource Prioritization: Optimize Loading OrderCode Splitting: Optimize Bundle Size with Dynamic ImportsTree Shaking: Eliminate Dead Code from Your BundleLazy Loading: Load Resources On-DemandResource Hints: Preload, Prefetch & PreconnectText Compression: Gzip and BrotliImage & Video Optimization: Modern Formats & TechniquesAdaptive Loading: Optimize for Device & NetworkList Virtualization: Render Large Lists EfficientlyWeb Workers vs Main Thread: Offloading Heavy WorkMemory Leaks in Frontend Apps: Detection & PreventionManaging Third-Party Scripts: Optimization StrategiesHow CDNs Work: Edge Delivery, Caching & PerformanceHTTP Caching Deep Dive: Cache-Control, ETag & RevalidationService Workers & Offline Strategy: Cache First, Network First & Update LifecyclePWA Fundamentals: Manifest, Installability & Offline UXCritical Rendering PathScript Loading: async vs deferEvent Loop: Understanding JavaScript Execution ModelJavaScript Module Systems: CJS vs ESM vs UMDDynamic Module Loading: import() FunctionImport on Interaction: Load When User InteractsImport on Visibility: Lazy Loading with IntersectionObserverBrowser Rendering Pipeline & Layout ThrashingRendering Strategies: CSR vs SSR vs SSG vs ISRStreaming SSR: Progressive HTML StreamingIslands Architecture: Independent Component HydrationReact Server Components: Zero-JS Server RenderingFramework Reactivity: React, Vue, Svelte & SolidHTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC) for Frontend PerformanceDNS Resolution: Path, TTL, Caching & Frontend ImpactCross-Site Scripting (XSS) AttacksCross-Site Request Forgery (CSRF) AttacksCORS Explained: Cross-Origin Resource SharingCORS Preflight in Practice: Credentials, Simple Requests & MisconfigurationsContent Security Policy (CSP)Why is HTTPS Secure? Understanding TLS/SSLAuthorization Best PracticesCookie Security & Session Hardening: SameSite, HttpOnly, Secure
mediumFrontend Architecture

Browser Storage: Cookies, SessionStorage, LocalStorage, IndexedDB

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.

PropertyCookiessessionStoragelocalStorageIndexedDB
SecurityHigh (with httpOnly)Medium (XSS risk)Medium (XSS risk)Medium (XSS risk)
Size Limit~4KB~5-10MB~5-10MBHundreds of MB
PerformanceSent on every requestSynchronousSynchronousAsynchronous
PersistenceConfigurableTab session onlyAcross sessionsAcross sessions
Server AccessYesNoNoNo

Cookies

Security

High (with httpOnly)

Size Limit

~4KB

Performance

Sent on every request

Persistence

Configurable

Server Access

Yes

sessionStorage

Security

Medium (XSS risk)

Size Limit

~5-10MB

Performance

Synchronous

Persistence

Tab session only

Server Access

No

localStorage

Security

Medium (XSS risk)

Size Limit

~5-10MB

Performance

Synchronous

Persistence

Across sessions

Server Access

No

IndexedDB

Security

Medium (XSS risk)

Size Limit

Hundreds of MB

Performance

Asynchronous

Persistence

Across sessions

Server Access

No

Common questions

  • ›“When would you use localStorage vs IndexedDB?”
  • ›“Why should auth tokens never be stored in localStorage?”
  • ›“What are the security risks of each storage type?”
  • ›“How do you choose the right storage mechanism for a feature?”

What interviewers look for

  • Strong security awareness (httpOnly cookies for tokens)
  • Clear understanding of persistence, size, and performance trade-offs
  • Knowledge of XSS risks and mitigation strategies (CSP)
  • Practical decision-making based on use case

Short answer (60 sec)

Cookies for server-accessible auth (httpOnly). sessionStorage for temporary tab data. localStorage for simple persistent preferences. IndexedDB for large, structured, or offline data. Never store sensitive tokens in client-side storage.

Detailed answer (senior level)

Each storage has a purpose: Cookies enable server access and strong security when httpOnly. sessionStorage is isolated per tab. localStorage persists but is synchronous and vulnerable to XSS. IndexedDB provides large capacity and powerful querying but requires an async API. Choose based on persistence needs, data size, security sensitivity, and whether server access is required. Always protect auth tokens with httpOnly cookies and implement CSP.

  • Storing JWT/auth tokens in localStorage
  • Using localStorage for large or frequently read data
  • Blocking the main thread with synchronous storage operations
  • Not handling quota exceeded errors gracefully
  • Assuming data in localStorage is private or secure
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
Previous TopicHow Frontend Developers Can Handle Millions of API Requests Without Crashing EverythingNext Topic Real-time Communication: WebSockets, SSE & Polling

On this page