FA Dev Tools

English中文

localStorage vs sessionStorage vs Cookies — How to Choose

web/localstorage-vs-sessionstorage-vs-cookies · By Derek Lam · Updated · 28 views · Tags: web, browser, storage, localstorage, sessionstorage, cookies, security

Written with claude-opus-5-5


TL;DR

  • localStorage keeps data until it is cleared, and every tab on the same origin shares it. Use it for preferences and drafts.
  • sessionStorage is one tab's copy. It survives a reload but is gone when the tab closes. Use it for state that belongs to one tab.
  • Cookies go to the server with every request. They are small (about 4 KB each) and can be hidden from JavaScript with HttpOnly.
  • Verdict: keep auth in an HttpOnly cookie, preferences in localStorage, per-tab state in sessionStorage, and big data in IndexedDB.

Contents

At a glance

localStoragesessionStorageCookies
How long it lastsUntil code, the user or the browser clears itUntil the tab or window closesSession cookie: until the browser closes. Persistent cookie: until Expires / Max-Age (Chrome caps it at 400 days)
Survives a reload✅✅✅
Survives closing the browser✅❌ (some browsers bring it back with "restore tabs")Persistent ✅, session ❌
Shared between tabs✅ every tab on the origin❌ each tab has its own copy✅ every tab
Duplicating a tabSharedThe new tab gets a copy taken at that momentShared
ScopeOrigin (scheme + host + port)Origin and tabDomain + path. Domain= can share it with subdomains; the port is ignored
Size limitAbout 5 MB per originAbout 5 MB per originAbout 4 KB per cookie, and a limit on how many per domain
Sent to the server❌❌✅ with every matching request, images and API calls included
Server can set it❌❌✅ Set-Cookie header
Readable on the server (SSR)❌❌✅ from the request headers
Hidden from JavaScript❌❌✅ with HttpOnly
JS APIgetItem / setItem, synchronous, strings onlyThe samedocument.cookie (one awkward string), or the async cookieStore API
Change event in other tabs✅ storage event❌cookieStore change event, where supported

Cookies are the only one of the three with security settings. Set them on purpose:

AttributeWhat it doesTypical value
HttpOnlyJavaScript can't read it, so an XSS bug can't steal itOn for session and auth cookies
SecureSent over HTTPS onlyAlways on in production
SameSiteWhether it's sent on cross-site requests. Strict = never, Lax = top-level navigation only, None = always (needs Secure)Lax (the browser default when it's left out)
Expires / Max-AgeMakes it a persistent cookie. Leave both out for a session cookieAs short as the feature allows
DomainShares it with subdomains (Domain=fishapple.com covers app.fishapple.com)Leave it out unless subdomains need it
PathOnly sent for URLs under this path/
__Host- name prefixThe browser refuses it unless it's Secure, Path=/ and has no DomainUse it for auth cookies

Every cookie for a domain rides along on every request to it, images and fonts included. Keep them few and small, and serve static files from a domain that has none.

What they have in common

  • Strings only. Objects need JSON.stringify / JSON.parse. Cookie values also need encodeURIComponent.
  • localStorage and sessionStorage are synchronous. Big reads and writes block the main thread. For more than a few hundred KB, use IndexedDB.
  • Any script on the page can read localStorage and sessionStorage, so an XSS bug exposes everything in them. A cookie is safe from that only when it's HttpOnly.
  • Neither web storage API exists during SSR, because window is undefined on the server. In Next.js, read them in useEffect or behind a typeof window !== "undefined" check. On the server, read cookies with cookies() from next/headers.
  • They can throw: quota exceeded, blocked storage, some private modes. Wrap the calls in try/catch.
  • Private and incognito windows keep all three only until the private session ends.
  • Safari can delete script-written storage (localStorage, and cookies set from JavaScript) after 7 days of browsing without a visit to the site. Cookies set by the server with Set-Cookie last longer.

Any script on the page can read localStorage, a compromised npm package or an injected ad included. Put session tokens in an HttpOnly, Secure, SameSite=Lax cookie.

Which one to use

Use casePick
Login session, auth tokenCookie: HttpOnly, Secure, SameSite=Lax
Something the server must know on the first request (locale, A/B bucket, theme for SSR without a flash)Cookie
Theme, language, UI preferences that only the browser needslocalStorage
"Remember my last choice" across visitslocalStorage
Form draft that should survive closing the browserlocalStorage
Multi-step form or wizard progress in one tabsessionStorage
Scroll position or filters for one tab onlysessionStorage
Two tabs doing different things that mustn't overwrite each othersessionStorage
Large or structured data (MB+, files, blobs)IndexedDB
Anything that must follow the user to another deviceThe server (a database), not the browser
flowchart TD
  A["Does the server need it<br/>on each request?"] -->|"Yes"| C["Cookie<br/>(HttpOnly if it's a secret)"]
  A -->|"No"| B["Is it a secret?"]
  B -->|"Yes"| C
  B -->|"No"| D["Bigger than a few hundred KB?"]
  D -->|"Yes"| I["IndexedDB"]
  D -->|"No"| E["Should it outlive the tab?"]
  E -->|"Yes"| L["localStorage"]
  E -->|"No, this tab only"| S["sessionStorage"]

Disclaimer: These documents are personal notes. The information may be incomplete, out of date or wrong, so check it before you rely on it.