Cookies are the oldest browser storage โ tiny, quirky, and still essential for one thing: they travel to the server with every request.
The awkward API
// writing โ one at a time, with flags
document.cookie = "theme=dark; max-age=31536000; path=/; SameSite=Lax";
// reading โ you get ONE string, parse it yourself
document.cookie; // "theme=dark; lang=ta; session=abc"
const get = (name) =>
document.cookie.split("; ").find((c) => c.startsWith(name + "="))?.split("=")[1];
// deleting = expiring
document.cookie = "theme=; max-age=0; path=/";The flags that matter (interview!)
- httpOnly โ JS cannot read it (server-set only). THE defense for session tokens against XSS
- Secure โ HTTPS only
- SameSite=Lax/Strict โ controls cross-site sending; the CSRF mitigation
- max-age / expires โ otherwise it dies with the session
The decision
Server needs it on every request (auth/session)? โ cookie (httpOnly, set by the server). Client-only preference (theme, drafts, progress)? โ localStorage โ 5MB vs 4KB, sane API, and it doesn't bloat every HTTP request. That one-paragraph answer covers the classic interview comparison.