Cookies vs localStorage
Cookies are small pieces of data the browser sends on matching HTTP requests. localStorage is a larger origin-scoped key/value store that JavaScript reads and writes and that is not sent automatically with every request.
Detailed Explanation
A cookie is set by Set-Cookie or document.cookie. The browser attaches it to later requests for the same site (plus rules for Domain, Path, SameSite, Secure). Size is small (about 4 KB per cookie). HttpOnly cookies are invisible to JavaScript, which is what you want for session tokens: XSS cannot document.cookie them. SameSite=Lax or Strict reduces CSRF; None requires Secure and is for cross-site iframes.
localStorage is localStorage.setItem(key, value) / getItem / removeItem. Values are strings. Quota is a few megabytes per origin. Data survives tabs and restarts until the user clears site data. It is never sent as a header. Any script on the origin can read it, so an XSS steals tokens stored there. There is no HttpOnly equivalent.
Use cookies (HttpOnly, Secure, SameSite) for auth sessions when the server should see the token on each request. Use localStorage for non-secret UI prefs, a draft, a cache of public data. Do not put refresh tokens in localStorage on a site that might have XSS.
sessionStorage is like localStorage but per tab; see that term. IndexedDB is for structured, larger data.
What it costs you: security mistakes. A JWT in localStorage plus one XSS is an account takeover. Cookies without SameSite plus a vulnerable GET action is CSRF. Also, localStorage is synchronous and can block on large reads; do not store megabyte JSON on the main thread without measuring.
Reach for HttpOnly cookies for sessions. Reach for localStorage for non-secrets. Reach for memory plus a cookie for the most sensitive apps.
Code Examples
localStorage.setItem("theme", "dark");
console.log(localStorage.getItem("theme")); // => dark
localStorage.removeItem("theme");Only non-HttpOnly cookies are visible:
// Only non-HttpOnly cookies are visible:
document.cookie = "sidebar=open; Max-Age=86400; SameSite=Lax; Path=/";
console.log(document.cookie.includes("sidebar=open"));function readJson(key, fallback) {
const raw = localStorage.getItem(key);
if (raw == null) return fallback;
try {
return JSON.parse(raw);
} catch {
return fallback;
}
}Common Gotchas
Tokens in `localStorage` are readable by any XSS
prefer `HttpOnly` cookies for sessions.
Cookies are sent on every matching request
a large cookie header wastes bandwidth and can break request size limits.
`localStorage` is per origin, shared by all tabs
a `storage` event fires in *other* tabs on change.
Private mode and user settings can throw `QuotaExceededError` or `SecurityError`
wrap writes.