FE Interview Hub
Browser InternalsBasic

What are the differences between cookie, sessionStorage, and localStorage?

AI Practice

Comparison of the three browser storage mechanisms

Feature Cookie sessionStorage localStorage
Capacity ~4 KB ~5–10 MB ~5–10 MB
Lifetime Configurable (default: session) Cleared when tab closes Persistent (manual clear)
Shared across tabs ✅ (same origin) ❌ (tab-scoped only) ✅ (same origin)
Sent with HTTP requests ✅ (in request header)
Accessible via JS ✅ (unless HttpOnly)
Security attributes HttpOnly, Secure, SameSite
  • Primary use: authentication (session ID, JWT), tracking, cross-request state
  • Automatically included in every HTTP request header — readable by the server
  • You can set an expiry (Expires / Max-Age); without one it becomes a session cookie (cleared when the browser closes)
  • Security attributes:
    • HttpOnly — JS cannot read it, protects against XSS token theft
    • Secure — only sent over HTTPS
    • SameSite — CSRF mitigation (Strict / Lax / None)
// Setting a cookie from JS
document.cookie = 'token=abc123; max-age=3600; path=/; Secure; SameSite=Lax';

sessionStorage

  • Primary use: temporary state within a single tab (form drafts, multi-step flows)
  • Automatically cleared when the tab is closed; not shared with new tabs
  • Same API as localStorage
sessionStorage.setItem('step', '2');
const step = sessionStorage.getItem('step');
sessionStorage.removeItem('step');
sessionStorage.clear();

localStorage

  • Primary use: user preferences, themes, language settings, local cache that doesn't need a backend
  • Data persists indefinitely until manually cleared or the user clears browser data
  • Shared across all tabs and windows of the same origin
localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme');
localStorage.removeItem('theme');
localStorage.clear();

localStorage only stores strings — use JSON.stringify / JSON.parse for objects.

Which to choose?

  • Needs to reach the server / authentication → Cookie (pair with HttpOnly + Secure)
  • Temporary state for a single tab, should not survive a new tab → sessionStorage
  • Persistent user settings or local caching → localStorage

✦ AI Mock Interview

Type your answer and get instant AI feedback

Sign in to use AI scoring