By Plainly Editorial

Updated

First published

Cookies vs local storage

Filed under Internet literacy

Keep session identifiers in cookies marked HttpOnly, Secure and SameSite=Lax or Strict, so injected scripts cannot read them and cross-site requests mostly cannot use them. Use localStorage for non-sensitive client state such as UI preferences, drafts and cached data that the server never needs. Neither is encrypted or a safe place for secrets: assume anything in localStorage is exposed by any XSS bug, and any cookie is attached to requests you did not intend unless you configure it carefully.

Side-by-side

DimensionCookiesLocal storage
Size limitAbout 4 KB per cookie; RFC 6265 asks browsers to support at least 4,096 bytes and 50 cookies per domainAbout 5 MiB per origin in major browsers; throws QuotaExceededError when full
Sent to the serverAutomatically, on every matching HTTP request, including images and scriptsNever, unless your code reads it and adds it to a request
Readable from JavaScriptYes via document.cookie, unless the cookie is HttpOnlyAlways, by any script running on that origin
Set byServer (Set-Cookie header) or client scriptClient script only
Security attributesHttpOnly, Secure, SameSite, Domain, Path, Partitioned, plus __Host- and __Secure- name prefixesNone; access control is the same-origin policy alone
ExpirySession (no expiry) or Expires/Max-Age; Chrome caps lifetimes at 400 daysNo expiry; stays until code or the user clears it, or the browser evicts it
ScopeDomain and path; can be shared with subdomains; not isolated by portExact origin: scheme, host and port
Data formatOne string per name, with restricted charactersString key-value pairs; objects need JSON.stringify
API styleHeader-based; awkward string parsing in document.cookieSimple synchronous getItem/setItem, which blocks the main thread
Main XSS riskHttpOnly cookies cannot be read, though injected scripts can still make requests that carry themAny injected script can read and exfiltrate everything stored
Main CSRF riskYes, because cookies attach automatically; SameSite and CSRF tokens mitigate itNo, because nothing is sent automatically
Available in workersNot via document.cookie; the Cookie Store API is available in some browsersNo; main thread only

Choose Cookies when

  • You manage a login session and the server must recognise the user on each request.
  • The value should be hidden from JavaScript, such as a session ID, so you need HttpOnly.
  • Server-rendered pages need the value on the first request, before any script runs.
  • You need the value shared across subdomains such as app.example.com and www.example.com.
  • You want the browser to expire the value on a schedule without client code.

Choose Local storage when

  • The data is only used in the browser, such as theme, layout or dismissed-banner flags.
  • You need more than a few kilobytes, such as autosaved form drafts.
  • Sending the value with every request would waste bandwidth, including on image and script requests.
  • You want simple synchronous reads for small values during page start-up.
  • You need state to persist across tabs and browser restarts, with storage events to sync open tabs.
  • The data is not sensitive, so exposure through an XSS bug would not hurt users.

Common questions

Should I store a JWT in localStorage or a cookie?

For browser sessions, an HttpOnly, Secure, SameSite cookie is usually the safer default, because an XSS bug cannot read it. A token in localStorage avoids CSRF but can be stolen by any injected script and replayed elsewhere. If you use cookies, add CSRF defences for state-changing requests; either way, keep tokens short-lived.

What is the difference between localStorage and sessionStorage?

Both use the same Web Storage API and origin scoping. sessionStorage is tied to one tab: it survives reloads but is cleared when the tab closes, and other tabs cannot see it. localStorage is shared by all tabs on the origin and persists until cleared. Use sessionStorage for per-tab state such as a multi-step form.

When should I use IndexedDB instead of localStorage?

Use IndexedDB for larger or structured data, such as offline app data, files or thousands of records. It is asynchronous, so it does not block the main thread, it stores objects and binary data without JSON conversion, it works in web workers, and quotas are far larger. It has the same XSS exposure as localStorage.

Does SameSite=Lax stop CSRF completely?

Not completely. Lax blocks cookies on most cross-site subrequests and form POSTs but still sends them on top-level GET navigations, so GET handlers must never change state. It also offers no protection against attacks from sibling subdomains, which count as same-site. Chromium treats cookies without SameSite as Lax, but not every browser does, so set it explicitly.

Does localStorage need consent under cookie laws?

EU and UK rules cover storing or reading any information on a user's device, not just cookies. Regulators such as the UK ICO apply them to localStorage and similar technologies. A purely functional value, like a theme the user chose, is likely strictly necessary; analytics or advertising identifiers generally need consent wherever you store them.

Can browsers delete localStorage without the user asking?

Yes. Storage is best-effort unless you request persistence with navigator.storage.persist(), and browsers can evict it under storage pressure. Safari can also delete script-written storage for sites a user has not interacted with recently. Treat localStorage as a cache, not a database of record, and keep anything important on the server.

Is localStorage shared with third-party iframes?

Not across sites in current major browsers. Storage in a third-party iframe is partitioned by the top-level site, so an embed on site A sees different localStorage from the same embed on site B. Cookies in third-party contexts behave differently by browser; the Partitioned attribute (CHIPS) gives them the same kind of per-site isolation.

Sources and further reading

  1. Using HTTP cookies — MDN Web Docs
  2. Set-Cookie header — MDN Web Docs
  3. Web Storage API — MDN Web Docs
  4. Storage quotas and eviction criteria — MDN Web Docs
  5. RFC 6265: HTTP State Management Mechanism — IETF / RFC Editor
  6. What are storage and access technologies? — Information Commissioner's Office (UK)

Keep reading