Trivia Questions2 min readPremium

localStorage vs sessionStorage vs Cookies

All three store small pieces of string data in the browser. They differ in how long the data lives, who can read it, and whether it’s sent to the server.

localStorage sessionStorage Cookies
Lifetime Until cleared Until the tab closes Session, or until Expires / Max-Age
Scope Origin, all tabs Origin, one tab Domain + path, all tabs
Capacity About 5 MB per origin About 5 MB per origin About 4 KB per cookie
Sent with HTTP requests No No Yes, automatically
Readable from JavaScript Yes Yes Yes, unless HttpOnly
Readable on the server No No Yes
API Synchronous key/value Synchronous key/value document.cookie string, or Set-Cookie header

1. localStorage

localStorage.setItem('theme', 'dark');
localStorage.getItem('theme');      // 'dark'
localStorage.removeItem('theme');

// Values are strings: serialise objects yourself
localStorage.setItem('draft', JSON.stringify({ title: 'Hello' }));
const draft = JSON.parse(localStorage.getItem('draft') ?? 'null');

Good for: preferences, UI state, drafts, cached non-sensitive data.

2. sessionStorage

Same API, but each tab gets its own copy and it’s cleared when the tab closes. It survives reloads. Duplicating a tab copies the data once; after that the two tabs are independent.

Good for: a multi-step form in progress, per-tab filters, a one-time redirect target.

3. Cookies

Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=604800
Attribute Effect
HttpOnly JavaScript can’t read it, so XSS can’t steal it
Secure Sent over HTTPS only
SameSite=Lax / Strict Limits cross-site sending, the main CSRF defence
Max-Age / Expires Persists beyond the session
Domain / Path Which requests include it

Good for: anything the server must see on each request, mainly sessions. Keep them small, because every request to the domain carries them.

4. Where should an auth token go?

The standard interview follow-up.

  • localStorage: simple, but any script on the page can read it. One XSS bug and the token is gone.
  • HttpOnly cookie: JavaScript can’t read it. The browser sends it automatically, so you need CSRF protection (SameSite, plus a token for state-changing requests if you support cross-site use).

For most web apps the recommendation is an HttpOnly, Secure, SameSite cookie, with short-lived sessions. More in frontend security best practices.

5. Gotchas

  • Synchronous. localStorage blocks the main thread. Don’t read large values in hot paths.
  • Can throw. Storage may be full or disabled. Wrap writes in try/catch.
  • Not available during server rendering. Guard with typeof window !== 'undefined', or read it in an effect.
  • No expiry. localStorage never expires on its own. Store a timestamp and check it yourself: expiring storage wrapper.
  • Cross-tab sync. The storage event fires in other tabs when localStorage changes, which is handy for logging out everywhere. For richer messaging use BroadcastChannel.
window.addEventListener('storage', (e) => {
  if (e.key === 'session' && e.newValue === null) redirectToLogin();
});

6. When none of them fit

For large or structured data (offline documents, cached API responses, files), use IndexedDB: asynchronous, much larger quota, and it stores objects, not just strings.

Choosing a storage type

Data Use
Theme, language, dismissed banners localStorage
Unsaved form in this tab sessionStorage
Session or auth HttpOnly cookie
A value the server needs on first render Cookie
Megabytes of data, offline support IndexedDB

Follow-up questions to expect

  • “Is sessionStorage shared between tabs?” No. Each tab has its own.
  • “Can JavaScript read an HttpOnly cookie?” No, which is the point.
  • “How would you clear everything on logout?” Clear storage keys, have the server expire the cookie, and broadcast the logout to other tabs.