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
HttpOnlycookie, preferences in localStorage, per-tab state in sessionStorage, and big data in IndexedDB.
Contents
At a glance
| localStorage | sessionStorage | Cookies | |
|---|---|---|---|
| How long it lasts | Until code, the user or the browser clears it | Until the tab or window closes | Session 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 tab | Shared | The new tab gets a copy taken at that moment | Shared |
| Scope | Origin (scheme + host + port) | Origin and tab | Domain + path. Domain= can share it with subdomains; the port is ignored |
| Size limit | About 5 MB per origin | About 5 MB per origin | About 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 API | getItem / setItem, synchronous, strings only | The same | document.cookie (one awkward string), or the async cookieStore API |
| Change event in other tabs | ✅ storage event | ❌ | cookieStore change event, where supported |
Cookie attributes
Cookies are the only one of the three with security settings. Set them on purpose:
| Attribute | What it does | Typical value |
|---|---|---|
HttpOnly | JavaScript can't read it, so an XSS bug can't steal it | On for session and auth cookies |
Secure | Sent over HTTPS only | Always on in production |
SameSite | Whether 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-Age | Makes it a persistent cookie. Leave both out for a session cookie | As short as the feature allows |
Domain | Shares it with subdomains (Domain=fishapple.com covers app.fishapple.com) | Leave it out unless subdomains need it |
Path | Only sent for URLs under this path | / |
__Host- name prefix | The browser refuses it unless it's Secure, Path=/ and has no Domain | Use 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 needencodeURIComponent. - 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
windowis undefined on the server. In Next.js, read them inuseEffector behind atypeof window !== "undefined"check. On the server, read cookies withcookies()fromnext/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-Cookielast 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 case | Pick |
|---|---|
| Login session, auth token | Cookie: 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 needs | localStorage |
| "Remember my last choice" across visits | localStorage |
| Form draft that should survive closing the browser | localStorage |
| Multi-step form or wizard progress in one tab | sessionStorage |
| Scroll position or filters for one tab only | sessionStorage |
| Two tabs doing different things that mustn't overwrite each other | sessionStorage |
| Large or structured data (MB+, files, blobs) | IndexedDB |
| Anything that must follow the user to another device | The 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.