Comparison
Cookies vs local storage
Quick verdict
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
| Dimension | Cookies | Local storage |
|---|---|---|
| Size limit | About 4 KB per cookie; RFC 6265 asks browsers to support at least 4,096 bytes and 50 cookies per domain | About 5 MiB per origin in major browsers; throws QuotaExceededError when full |
| Sent to the server | Automatically, on every matching HTTP request, including images and scripts | Never, unless your code reads it and adds it to a request |
| Readable from JavaScript | Yes via document.cookie, unless the cookie is HttpOnly | Always, by any script running on that origin |
| Set by | Server (Set-Cookie header) or client script | Client script only |
| Security attributes | HttpOnly, Secure, SameSite, Domain, Path, Partitioned, plus __Host- and __Secure- name prefixes | None; access control is the same-origin policy alone |
| Expiry | Session (no expiry) or Expires/Max-Age; Chrome caps lifetimes at 400 days | No expiry; stays until code or the user clears it, or the browser evicts it |
| Scope | Domain and path; can be shared with subdomains; not isolated by port | Exact origin: scheme, host and port |
| Data format | One string per name, with restricted characters | String key-value pairs; objects need JSON.stringify |
| API style | Header-based; awkward string parsing in document.cookie | Simple synchronous getItem/setItem, which blocks the main thread |
| Main XSS risk | HttpOnly cookies cannot be read, though injected scripts can still make requests that carry them | Any injected script can read and exfiltrate everything stored |
| Main CSRF risk | Yes, because cookies attach automatically; SameSite and CSRF tokens mitigate it | No, because nothing is sent automatically |
| Available in workers | Not via document.cookie; the Cookie Store API is available in some browsers | No; 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
- Using HTTP cookies — MDN Web Docs
- Set-Cookie header — MDN Web Docs
- Web Storage API — MDN Web Docs
- Storage quotas and eviction criteria — MDN Web Docs
- RFC 6265: HTTP State Management Mechanism — IETF / RFC Editor
- What are storage and access technologies? — Information Commissioner's Office (UK)
Keep reading
- What are cookies on websites?
A cookie is a small piece of text that a website asks your browser to store and send back on later visits. Cookies keep you logged in, remember your basket and settings, and measure traffic. Third-party cookies, set by companies other than the site you are on, can also be used to follow you across many sites for advertising.
- What is phishing?
Phishing is a scam in which someone pretends to be a trusted person or organisation to trick you into revealing passwords or payment details, clicking a harmful link, or sending money. It arrives by email, text, phone call, social media or QR code, and usually relies on urgency or fear to make you act fast.
- What is a password manager?
A password manager is an app that creates, stores and fills in your passwords for you. Your logins are kept in an encrypted vault that you unlock with one master password, a device PIN or your fingerprint. It lets you use a different strong password on every site without having to remember any of them.
- What are app permissions?
App permissions are the device or browser gates that control what an app can access—camera, microphone, location, photos, contacts, notifications, and more. Good hygiene means granting only what the feature needs, when it needs it.
- What is a VPN?
A VPN (virtual private network) is an encrypted tunnel between your device and a server run by someone else. Your local network and internet provider see only scrambled traffic going to that server, and websites see the server's IP address instead of yours. It does not make you anonymous: the VPN provider can now see what your ISP used to.