What is the difference between cookies, localStorage and sessionStorage?

JavaScript Browser Intermediate 1–2 Yrs2–3 Yrs3–5 Yrs Conceptual 1 min read

Quick Answer

Cookies — small (~4 KB), sent automatically with every request to the domain, can be HttpOnly (invisible to JS, safer for auth) and Secure/SameSite. localStorage — ~5–10 MB, persists until cleared, JS-only, same across tabs. sessionStorage — same as localStorage but scoped to one tab and cleared when it closes.

Cookies are tiny and get attached to every HTTP request to that domain automatically, and they can be marked HttpOnly so JavaScript can't read them, which is why they're the safer place for a session or auth token — an XSS bug can't just read it. localStorage is bigger, sticks around permanently, is shared across all tabs of the origin, and is only accessible from JS. sessionStorage is the same but per-tab and wiped when the tab closes. The security point I always raise: putting a JWT in localStorage means any script that gets injected can exfiltrate it.

  • Auth tokens: an HttpOnly cookie resists XSS token theft; a token in localStorage is readable by any injected script.
  • Cookies add overhead to every request — don't store large or non-auth data in them.
  • localStorage access is synchronous and can be a jank source for large blobs; use IndexedDB for bigger structured data.
  • None of them are safe for secrets on a shared machine.