Cookies vs Local Storage vs Session Storage — What's the Difference?

All three store data in the browser, but differ in size limits, lifetime, and whether they're automatically sent to the server with every request.

Published October 4, 2026

Cookies are small, sent to the server on every request and can expire; localStorage keeps data in the browser until cleared; sessionStorage keeps it only until the tab closes. Neither storage API sends data to the server automatically.

The concept

Cookies (~4 KB) carry session IDs and are controlled with flags like HttpOnly, Secure and SameSite. localStorage and sessionStorage hold about 5 MB of strings and are readable by any script on the page.

Because JavaScript can read localStorage, an XSS bug can steal anything stored there, so avoid putting auth tokens in it.

Comparison

cookie localStorage sessionStorage
size ~4 KB ~5 MB ~5 MB
sent to server yes no no
lifetime set by you until cleared tab session
JS-readable unless HttpOnly yes yes

Practical examples

localStorage

localStorage.setItem('theme', 'dark')
localStorage.getItem('theme')

sessionStorage

sessionStorage.setItem('draft', JSON.stringify(form))

Secure cookie from the server

Set-Cookie: sid=abc; HttpOnly; Secure; SameSite=Lax; Max-Age=3600

JSON values

localStorage.setItem('cart', JSON.stringify([1, 2]))
const cart = JSON.parse(localStorage.getItem('cart') ?? '[]')

Common mistakes

  • Storing JWTs or secrets in localStorage.
  • Forgetting storage only holds strings.
  • Assuming data persists in private browsing.

Key takeaways

  • Cookie = server-visible, small, flaggable.
  • localStorage = persistent, sessionStorage = per tab.
  • Use HttpOnly cookies for auth.

FAQ

Do they work across subdomains?

Cookies can (via Domain); web storage is per origin.

How much can I store?

Roughly 5 MB per origin for web storage.

More JavaScript articles