localStorage vs sessionStorage vs Cookies
A common browser-storage interview question. The three differ in lifetime, size, and whether the server ever sees them.
Lifetime & size
localStorage holds ~5–10MB and persists until cleared. sessionStorage is the same size but clears when the tab closes. Cookies are tiny (~4KB) and are sent to the server on every HTTP request.
localStorage.setItem("theme", "dark"); // persists
sessionStorage.setItem("step", "2"); // per-tab
document.cookie = "token=abc; Secure; SameSite=Strict";Which to use
Use localStorage for durable client-only preferences, sessionStorage for per-tab flow state, and cookies for anything the server needs on each request — like auth tokens (prefer httpOnly + Secure + SameSite cookies for those).
Master the browser-side questions
Storage, events, the DOM and performance — the browser questions every frontend round asks, in the JavaScript Interview Kit.
⚡ Get the JavaScript Interview Kit → ₹299Frequently asked questions
- Where should I store a JWT?
- For security, an httpOnly, Secure, SameSite cookie is preferred — JavaScript can't read it, which mitigates XSS token theft. Avoid localStorage for sensitive tokens.
- Are these sent to the server?
- Only cookies are sent automatically with requests. localStorage and sessionStorage are JS-only.
