12. Storage, Cookies and Offline
“A cookie is a note the server pins to your shirt, and you wear it to every single meeting with that server, forever, including the ones where it’s irrelevant.”
The story: the cloakroom token
Section titled “The story: the cloakroom token”You walk into a restaurant and hand over your coat. The attendant gives you a small brass token: number 47. You don’t carry the coat around; you carry the token. When you leave, you show the token, and you get your coat.
HTTP is a forgetful waiter. Every request is a stranger. Cookies are the token: the server hands you a small value (“session 47”), your browser shows it on every subsequent request, and the server looks up who you are.
Now, the restaurant also has a coat-check rule: show your token at every table you visit, every time you ask for anything — water, the menu, salt. That’s the hidden cost of cookies: they ride along on every request to their domain, including requests for images and CSS that don’t care who you are.
And sometimes, you want to keep something yourself — a shopping list, a book you’re reading offline. For that, the browser gives you your own pockets: localStorage, IndexedDB, the Cache API, the Origin Private File System. Each pocket has a different shape, a different speed, and a different chance of being emptied without warning.
Cookies in full
Section titled “Cookies in full”A server sets a cookie with a response header:
Set-Cookie: sid=abc123; Path=/; Max-Age=2592000; Secure; HttpOnly; SameSite=LaxThe browser stores it and sends Cookie: sid=abc123 on matching future requests. The attributes decide which requests:
Domain— which hosts receive it. Omit it and the cookie is host-only (just the exact host that set it). SetDomain=lumen.example.inand it’s sent to that host and all subdomains. Narrower is safer.Path— URL path prefix. Rarely a security boundary; mostly organizational.Expires/Max-Age— lifetime. Without either, it’s a session cookie, deleted when the browser session ends (which, with session restore, may be “never”).Secure— only sent over HTTPS.HttpOnly— not readable by JavaScript (document.cookiecan’t see it). Session cookies should always beHttpOnly, so an XSS bug (Chapter 13) can’t steal them.SameSite— whether the cookie is sent on cross-site requests:Strict: only when the request originates from the same site. Even following a link from another site to yours won’t send it (so you’d appear logged out on arrival).Lax: sent on same-site requests and on top-level navigations with safe methods (clicking a link to you). Not sent on cross-site subresource requests, iframes, or cross-site POSTs. Chrome madeLaxthe default for cookies without aSameSiteattribute in 2020, which quietly killed a large class of CSRF attacks (Chapter 13) and broke a lot of embedded widgets.None: sent on all cross-site requests; must be paired withSecure. Needed for genuine cross-site use (embedded widgets, some SSO flows).
Partitioned— part of CHIPS (Cookies Having Independent Partitioned State). A third-party cookie that’s partitioned is stored per top-level site: an embedded chat widget on site A and on site B gets two separate cookie jars, so it works as an embed but can’t track you across sites.
The third-party cookie saga
Section titled “The third-party cookie saga”A third-party cookie is one set by a domain other than the site in the address bar — typically an ad or analytics script or iframe on many sites, recognizing you everywhere. For two decades this powered cross-site tracking.
Safari (with Intelligent Tracking Prevention, from 2017) and Firefox (Enhanced Tracking Protection) progressively blocked or partitioned third-party cookies by default. Google announced in 2020 that Chrome would phase them out, built a suite of replacement “Privacy Sandbox” APIs, delayed repeatedly under regulatory and industry pressure, and in 2024–2025 ultimately backed away from forcing deprecation, moving towards user choice and then winding down much of the Privacy Sandbox effort. Net result as of late 2026: third-party cookies are blocked by default in Safari and Firefox, still available in Chrome unless the user blocks them, and you should build as if they don’t exist: use first-party cookies, partitioned cookies (CHIPS) for embeds, and explicit login flows for cross-site identity.
Cookie size and per-request overhead
Section titled “Cookie size and per-request overhead”Browsers allow roughly 4 KB per cookie and a limited number per domain. The real cost is that every request to the cookie’s domain carries all its cookies: every image, every script, every API call. A site with 3 KB of cookies (analytics IDs, A/B test buckets, consent strings) sends 3 KB uphill — and mobile upload is slower than download — on every one of its hundred requests. HTTP/2’s header compression (HPACK) helps a lot for repeated cookies on one connection, but the cookies still have to be sent once per connection and parsed every time.
Mitigations: keep cookies small; scope them with host-only domains; serve static assets from a cookieless domain or path; don’t use cookies for client-only state (that’s what localStorage is for).
Web Storage: localStorage and sessionStorage
Section titled “Web Storage: localStorage and sessionStorage”localStorage.setItem('theme', 'dark'). Simple key–value string storage per origin, persistent across sessions. sessionStorage is the same but per tab and cleared when the tab closes.
The catch: it’s synchronous. localStorage.getItem() blocks the main thread until the value is read. Browsers load an origin’s localStorage into memory, usually on first access — and on a slow device with a large store, that first access can block for a noticeable time. Also: strings only (you’ll JSON.stringify everything), small quotas (around 5 MB per origin), no transactions, not available in workers or service workers.
Use it for small, simple preferences: theme, a dismissed banner, a draft of a short form. Never for large data, never in hot paths, never for anything secret (any XSS can read it).
IndexedDB: the real database
Section titled “IndexedDB: the real database”IndexedDB is a transactional, asynchronous, object database built into every browser. It stores structured clones of JS values — objects, arrays, Blobs, ArrayBuffers — far beyond localStorage’s limits.
Concepts:
- Database per origin, with a version number. Schema changes happen in an
upgradeneededhandler when you open with a higher version (this is IndexedDB’s migration system). - Object stores — like tables. Each record has a key (a key path like
id, or auto-increment). - Indexes — secondary lookups on a property (
byDate,byTag). - Transactions — every read/write happens inside one,
readonlyorreadwrite, scoped to specific stores. Transactions auto-commit when there’s no more pending work — which is the source of a classic bug: if youawaitsomething unrelated (afetch) inside a transaction, it commits and closes under you. - Cursors — iterate over ranges of records.
The raw API is event-based and verbose; nearly everyone uses a thin Promise wrapper like idb (a few KB) or a higher-level library (Dexie). With idb:
import { openDB } from 'idb';const db = await openDB('lumen', 1, { upgrade(db) { const s = db.createObjectStore('essays', { keyPath: 'slug' }); s.createIndex('bySavedAt', 'savedAt'); },});await db.put('essays', { slug: 'monsoon', html, savedAt: Date.now() });const recent = await db.getAllFromIndex('essays', 'bySavedAt');IndexedDB is the right home for offline data, caches of API responses, drafts, and anything sizeable.
The Cache API and OPFS
Section titled “The Cache API and OPFS”- Cache API —
caches.open('v3')gives you a store of Request → Response pairs. Designed for service workers, available on the page too. Perfect for caching network responses (HTML, JS, images) for offline use. It has nothing to do with the HTTP cache (Chapter 6) — it’s a separate store you control explicitly. - Origin Private File System (OPFS) — a private, sandboxed file system per origin, with a very fast synchronous access mode in workers. It’s what makes running SQLite (compiled to WebAssembly) in the browser practical, and suits large binary files.
Quotas, eviction and persistence
Section titled “Quotas, eviction and persistence”Browsers give each origin a share of disk space (generous in Chromium — a large fraction of free disk; different policies in Firefox and Safari). Check with navigator.storage.estimate().
Storage is best-effort by default: when the device runs low on space, the browser may evict an origin’s data — all of it, atomically — typically least-recently-used origins first. You can ask for persistent storage with navigator.storage.persist(); browsers grant it based on signals (installed PWA, site engagement, bookmarks) or a permission prompt, and persistent data is not evicted without user action.
Safari’s special rule: with Intelligent Tracking Prevention, Safari deletes all script-writable storage (localStorage, IndexedDB, service worker registrations, Cache API) for a site after seven days of Safari use without the user interacting with that site — unless it’s a home-screen web app. It’s an anti-tracking measure with a big side effect: your “offline-first” app’s data on iOS can silently vanish if the user doesn’t visit for a week. Design for it: treat client storage as a cache that can disappear, with the server as source of truth.
Service workers: a programmable proxy in the browser
Section titled “Service workers: a programmable proxy in the browser”A service worker is a script that the browser runs in the background, separate from your pages, which can intercept every network request your pages make (within its scope) and decide how to answer: from the network, from a cache, or by constructing a response. It’s the foundation of offline support, PWAs and push notifications.
Lifecycle
Section titled “Lifecycle”- Register: your page calls
navigator.serviceWorker.register('/sw.js'). - Install: the browser downloads
sw.jsand firesinstall. You typically precache the app shell here (HTML, CSS, JS, icons) into the Cache API. - Waiting: if an older service worker is currently controlling open pages, the new one waits — it won’t take over until every tab using the old version is closed. This avoids two versions of your app fighting over the same caches.
- Activate: once the old one is gone (or you call
skipWaiting()),activatefires. Clean up old caches here. - Fetch: the active worker receives
fetchevents for requests from pages it controls, and answers them.
The browser checks for an updated sw.js on navigations (byte-for-byte comparison), at most roughly daily even if your HTTP caching says otherwise.
Caching strategies
Section titled “Caching strategies”Inside fetch, you pick a strategy per kind of request:
- Cache first (falling back to network): instant, works offline; content may be stale. For hashed static assets, fonts, icons.
- Network first (falling back to cache): fresh when online, works offline with last-known content; slow on bad networks (you wait for the network to fail or time out). For HTML of frequently changing pages, API data where freshness matters.
- Stale-while-revalidate: answer from cache immediately, fetch an update in the background for next time. Great default for content that can be slightly stale (avatars, article lists).
- Network only / cache only: for things that must be live (payments) or must be local.
Libraries like Workbox package these strategies, precache manifests and expiration rules, and they’re worth using: hand-written service workers are a famous source of subtle bugs.
The classic bug: users stuck on an old version
Section titled “The classic bug: users stuck on an old version”You deploy a new version. Users report they still see the old site — for days. What happened?
- Your service worker serves the HTML from cache first. The cached HTML references the old hashed JS. So the old app keeps loading, offline-fast, forever.
- The new service worker installed but is waiting, because the user never closes the tab (on mobile, tabs live for weeks).
- Or your server sent
sw.jsitself with a long cache lifetime, so the browser took longer to notice the update.
Fixes: don’t cache-first your HTML (network-first or stale-while-revalidate for navigations); serve sw.js with Cache-Control: no-cache; implement an update flow — when a new worker is waiting, show “A new version is available — Refresh,” which calls skipWaiting() and reloads once the new worker activates; version and clean up caches on activate. And keep a kill switch: a no-op service worker you can deploy that unregisters itself and clears caches, in case you ship something broken.
PWAs and the manifest
Section titled “PWAs and the manifest”A Progressive Web App is a website with a web app manifest (manifest.webmanifest: name, icons, theme colour, display mode, start URL) and usually a service worker. Browsers can then offer to install it: home-screen icon, standalone window, launch without browser UI. On Android, installed PWAs feel close to native; on iOS, PWAs added to the home screen have gained push notifications and other capabilities over the years, with more limits than Android.
What to store where
Section titled “What to store where”| Data | Where | Why |
|---|---|---|
| Session/auth token | HttpOnly; Secure; SameSite=Lax cookie |
Unreadable by JS (XSS-safe), sent automatically to your server |
| CSRF token | cookie + header pattern, or framework mechanism | See Chapter 13 |
| Theme, small UI prefs | localStorage | Tiny, synchronous read at startup is OK |
| Short-lived per-tab state (wizard step) | sessionStorage | Clears with the tab |
| Offline essays, drafts, API data caches | IndexedDB | Large, structured, async |
| Offline HTML/JS/CSS/images | Cache API via service worker | Request/response shaped |
| Large files, SQLite-in-the-browser | OPFS | Fast file I/O in workers |
| Anything secret (API keys, other users’ data) | Nowhere on the client | Client storage is readable by the user and any XSS |
| Analytics IDs | first-party cookie or localStorage, minimal | Respect consent (Chapter 23) |
What you now know
Section titled “What you now know”You can read and write Set-Cookie with every attribute, explain SameSite modes and the 2020 default change, CHIPS, and the third-party cookie saga; explain why localStorage’s synchronicity matters; use IndexedDB’s stores, indexes, transactions and versions; distinguish the Cache API from the HTTP cache; reason about quotas, eviction, persistence and Safari’s 7-day rule; and run a service worker without trapping users on old versions.
Self-quiz
Section titled “Self-quiz”1. What does HttpOnly protect against?
JavaScript (including injected XSS) reading the cookie via document.cookie.
2. With SameSite=Lax, is the cookie sent when another site embeds your page in an iframe?
No. Lax cookies go on same-site requests and top-level safe navigations only.
3. Why can IndexedDB transactions “close unexpectedly”?
They auto-commit when no requests are pending; awaiting unrelated async work (like fetch) lets them commit.
4. Why does a new service worker sometimes not take effect?
It waits until all tabs controlled by the old worker close (unless skipWaiting is used).
5. What’s Safari’s 7-day rule?
Script-writable storage for a site is deleted after seven days of Safari use without user interaction with that site (non-installed web apps).
Exercises
Section titled “Exercises”Warm-up 1. Fix the cookie. Set-Cookie: session=xyz; Domain=example.com — list what’s missing for a session cookie and why.
Solution
Add Secure (HTTPS only), HttpOnly (no JS access), SameSite=Lax (explicit CSRF protection), a sensible Max-Age, and consider dropping Domain to make it host-only.
Warm-up 2. Where does it go? A 2 MB JSON of offline recipes; the user’s preferred language; a payment card number.
Solution
IndexedDB; localStorage (or a cookie if the server needs it); nowhere — payment data goes to the payment provider, never client storage.
Warm-up 3. Count the bytes. A page makes 80 requests to its own domain, with 2.5 KB of cookies. How much cookie data goes uphill on HTTP/1.1? Why is it less on HTTP/2?
Solution
~200 KB on HTTP/1.1. HTTP/2 compresses repeated headers with HPACK, so after the first request the cookie costs a few bytes per request.
Lab 4. Lumen’s reading list. Add “Save for offline” to Lumen essays: store essay HTML and images’ URLs in IndexedDB via idb, and list saved essays on /saved.
Expected outcome
Saved essays appear in DevTools → Application → IndexedDB. The list loads without network.
Lab 5. Offline Lumen. Add a service worker (Workbox or hand-written) with: precached app shell, cache-first for hashed assets, network-first for navigations, stale-while-revalidate for images. Test offline in DevTools.
Expected outcome
Saved essays and the shell work offline; online navigations show fresh HTML.
Lab 6. The update flow. Deploy a new Lumen version with your service worker in place. Implement and test a “new version available — refresh” toast.
Hint
Listen for the registration’s updatefound/waiting state; on click, message the waiting worker to skipWaiting(), and reload on controllerchange.
Lab 7. Quota check. Show Lumen’s storage usage and quota on /saved using navigator.storage.estimate(), and request persistence.
Expected outcome
Usage/quota numbers displayed; persist() returns true or false depending on browser heuristics.
Staff 8. Offline-first proposal. Your PM wants the app “fully offline.” Write a half-page scoping the real trade-offs: storage eviction, Safari’s rule, conflict resolution, update flows, testing cost.
Model points
Define which features work offline; server stays source of truth; sync and conflict policy; eviction and iOS behaviour; service-worker rollback plan; test matrix; estimate effort honestly.
Staff 9. Cookie audit. List every cookie your production site sets (or a big site’s). For each: purpose, attributes, size, which requests carry it. Propose reductions.
Model approach
Use the Application panel; flag missing Secure/HttpOnly/SameSite, overly broad Domain, cookies used only by client JS (move to localStorage), and large consent/A-B cookies sent with static assets.