๐Ÿช JavaScript

Cookies in JavaScript โ€” And Why You Usually Want localStorage

๐Ÿ“… Jul 4, 2026 โฑ 3 min read

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!)

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.

โ† All Articles