What you'll learn: By the end of this lesson you will be able to name the places a web page can keep data (a variable, cookies,
sessionStorage,localStorage, IndexedDB, the Cache API), say for each what it holds, whether it blocks, who can read it, how long it lives and what it costs, rule out the wrong ones for a given need, and explain why "which store" is a question about the data, not about habit.
Think of the things you carry on a day out. Your pockets hold a few small items and are empty when you change clothes. A backpack stays with you until the day ends. A locker stays put as long as you rent it. A warehouse takes pallets, but you need a form to get anything out. A delivery slip is taped to every parcel you send, wanted or not. The browser offers all five, and the usual mistake is putting a parcel in a pocket because the pocket was nearest.
The running example is a shop's product page (made up for the lesson): a theme choice, a signed-in session, a checkout step, a catalogue that should work offline, and responses worth keeping for a flaky network. Each of them belongs somewhere different.
The core idea
- Every store is a bundle of constraints. What it can hold (strings or structured values), whether a call blocks, whether the browser attaches it to requests, whether workers can reach it, how long it lasts and who can read it. Choosing a store means choosing which constraints the data can live with.
- Start from what the data needs, then rule stores out. The documentation states most constraints plainly: strings only, synchronous, sent with every request, about 4 KB per cookie. A short list of needs removes most options before taste comes into it.
- The smallest scope that works is the safest. A value kept in memory cannot leak through a store. A value kept for one tab cannot confuse another. Widen the scope only when a requirement demands it.
Three illustrations run through the lesson. The minimal example is a theme preference. The realistic example is the product page's six pieces of data. The failure example is a value that fits no store you reach for first.
The six places
MDN lists the browser's storage choices. This lesson uses six, adding plain memory as the baseline.
| Place | Holds | Access | Sent with requests | In workers | Lifetime and scope |
|---|---|---|---|---|---|
| Variable in memory | Any JavaScript value | Synchronous | No | Each worker has its own | Until reload or close; one page |
| Cookie | Strings, about 4 KB each | Synchronous through document.cookie |
Yes, automatically | document.cookie is not available |
Session, or until Max-Age or Expires; host, path |
sessionStorage |
Strings | Synchronous | No | Not available | The page session (a reload keeps it); origin and tab |
localStorage |
Strings | Synchronous | No | Not available | No expiry; origin, shared by all tabs |
| IndexedDB | Anything the structured clone algorithm supports, including files and blobs | Asynchronous, transactional | No | Available | Best-effort; origin |
| Cache API | Request and Response pairs | Asynchronous | No | Available | No expiry; origin; HTTPS only |
Figure 1. Where each store sits
How to read this: the page talks to Web Storage and the jar with plain calls and to IndexedDB through asynchronous transactions. The arrow into the server is the odd one out: the browser follows it by itself, with whatever the jar holds for that URL.
The Cache API (not drawn) sits beside IndexedDB and holds network responses.
What the table does not say: how much fits
Cookies are limited to about 4 KB each (RFC 6265 asks browsers for at least 4096 bytes per cookie, and MDN says "usually 4KB"), plus a per-domain count that varies by browser. MDN's page on storage quotas gives Web Storage 5 MiB for localStorage and 5 MiB for sessionStorage per origin. IndexedDB, the Cache API and the Origin Private File System share a browser-managed quota per origin, and each browser decides the maximum itself, so this lesson gives no number for them: look it up for the browsers you support.
By default that data is best-effort: it persists while the origin is below its quota, the device has space and the user does not delete it. An origin can ask for persistent storage with navigator.storage.persist(), after which the data is evicted only if the user chooses. When a browser evicts an origin's data, MDN says all of it goes at once. MDN also notes that Safari evicts script-created data of an origin the user has not interacted with for seven days when cross-site tracking prevention is on, and that cookies set by the server are exempt. Treat anything in a store as a cache that can disappear.
Three questions that settle most choices
Does the server need to see it on every request? Only a cookie is attached to requests automatically. Putting a session id anywhere else means copying it into a header by hand, which is a legitimate pattern, but one where script reads the value. For credentials, see Token Storage and Secure Cookies. Conversely, a value the server does not need should not be a cookie: MDN warns that cookies "are sent with every request, so they can worsen performance", and says modern storage APIs "never send data to the server".
Is the value a string, or does it need to stay what it is? Web Storage and cookies hold strings only. MDN's example shows that storing an object gives "[object Object]", so you serialize, for example with JSON.stringify, and a Date or Set does not survive that (State Persistence and Synchronization covers the losses). IndexedDB uses the structured clone algorithm and stores richer values directly.
Can the code afford to block, and where does it run? MDN states that both Web Storage areas are synchronous: they block other JavaScript until the call finishes, which matters for large values. IndexedDB and the Cache API are asynchronous, and both are available in Web Workers. Web Storage is not in MDN's list of APIs available to workers, and the HTML Standard defines localStorage and sessionStorage on Window. A worker that needs data should use IndexedDB or get it by message from the page, see Web Workers and Offloading.
Figure 2. A decision path through the three questions
every request?"} -->|"yes, under 4 KB"| C["Cookie"] A -->|"yes, bigger"| X["No store fits:
change the design"] A -->|"no"| B{"A network
response?"} B -->|"yes"| H["Cache API"] B -->|"no"| D{"Large, structured
or used in a worker?"} D -->|"yes"| I["IndexedDB"] D -->|"no"| L{"How long must
it live?"} L -->|"this page"| M["Memory"] L -->|"this tab"| S["sessionStorage"] L -->|"across visits"| LS["localStorage"]
How to read this: each question removes options. The branch labelled "No store fits" is the important one: a value the server must see that does not fit in a cookie is a design problem, not a storage problem.
Illustration 1 (minimal): a theme preference
The value is the string dark. It must survive visits and nothing else needs it. Memory is gone on reload, sessionStorage is gone when the tab closes, and a cookie would add bytes to every request for nothing. That leaves localStorage.
Illustration 2 (realistic): the product page
The shop's page has six pieces of data. The lab below reasons about each one. Here is the start of its output for the first two (the full capture is in the next section).
Expected output, captured from a real run (Node 26.13.1, 2026-12-01, the first two needs of section 2):
=== 2. Which store fits which need
Theme preference ('dark') [text, 4 bytes, across-visits]
viable: localStorage, indexedDB
no memory: gone on reload
no sessionStorage: gone when the tab closes
no cookie: sent with every matching request: every call pays for the bytes
no cacheApi: stores Request/Response pairs, not plain values
Session id the server must see [text, 40 bytes, across-visits]
viable: cookie
cookie: needs Max-Age or Expires, or it is a session cookie
no memory, sessionStorage, localStorage, indexedDB: never sent with requests: you would copy it into a header by hand
no cacheApi: stores Request/Response pairs, not plain values
The session id is the clean cookie case and the theme is its mirror image. The other four needs (a checkout step for one tab, an offline catalogue read in a worker, a review draft with a Date, and API responses for offline use) land on sessionStorage, IndexedDB, IndexedDB and the Cache API.
Illustration 3 (failure): a value no store fits
A team wants the server to see a 6000-byte value on every request, so they reach for a cookie. At about 4 KB per cookie it does not fit, and every other store is ruled out for the reason that it is never sent. The lab ends with viable: none. The honest answer is that no browser store solves this: keep the data on the server under a short id, or send it in the body of the request that needs it. The cookie holds the id.
Figure 3. What each request carries
How to read this: the Cookie header appears on every request the jar matches, including ones for images. The theme in Web Storage is only ever seen by script, which is exactly why it costs nothing on the wire and also why a server cannot read it.
Build it: the choosing rules, runnable
Goal. Run a table of the documented facts and a function over it, and see which stores each need leaves possible.
Setup. The lab is in the course's example workspace (Node 26.13.1). It is a pure model of documented rules, not a browser.
cd examples/frontend
pnpm install
cd labs/storage-chooser
pnpm test # 20 tests
node src/demo.ts
Steps.
- Run the tests, then the demo.
- In section 2, read the reason attached to each rejection: each applies a sentence from the table above.
- In section 3, notice the two needs where the first viable store is not the smallest scope: the catalogue and the review draft. They send IndexedDB to the front because a worker or a rich value rules out the string stores.
Expected output, captured from a real run (Node 26.13.1, 2026-12-01, section 3):
=== 3. The first viable store, which is the one this lab prefers
localStorage <- Theme preference ('dark')
cookie <- Session id the server must see
sessionStorage <- Checkout step, this tab only
memory <- Search box text while typing
indexedDB <- Product catalogue for offline use
indexedDB <- Review draft with a Date and a Set
cacheApi <- API responses kept for offline
(none) <- A 6000-byte value the server must see
What the lab does not show. It runs no browser and measures nothing, the preference order is the lab's own choice, and it states no quota.
Break it. In src/choose.ts, delete the check that rejects a cookie when the server does not need it. The test "a value the server does not need is rejected as a cookie because of the per-request cost" fails, and the theme preference starts listing a cookie. Revert it.
In practice: a checkout that forgot its cart
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A storefront keeps the whole cart as JSON in a cookie so the server can render the cart count on every page. Carts are small at first. Over a few weeks customers add more items, and the page also loads many images from the same site.
Starting architecture
Figure 4. Starting point: the cart travels in a cookie
How to read this: the cart sits in the one store the browser sends by itself, so its size is added to every request, including the ones that have nothing to do with the cart.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Compress or shorten the cart JSON | Slower growth | A format to maintain | Still capped at about 4 KB, still on every request |
Move the cart to localStorage |
No bytes on requests | The server cannot render the count | A second tab or a new device sees a different cart |
Keep the cart on the server under a short cart id in a cookie; keep the theme in localStorage |
Small constant request cost, one cart for all tabs and devices | A server-side cart and an id lifecycle | The id must be protected like any session value |
The decision
| Field | Decision record |
|---|---|
| Context | The cart is data of record, the server needs the count, and the cookie is capped at about 4 KB and sent with every request. |
| Decision | Store the cart on the server. Keep only a short cart id in a cookie. Keep the theme in localStorage, the checkout step in sessionStorage, and the offline catalogue in IndexedDB. |
| Consequences, good | Request size stops depending on cart size, and every tab and device sees one cart. |
| Consequences, bad | The cart needs a server store and a way to merge a guest cart into an account later. |
| Revisit when | Offline carts become a requirement: then a local copy in IndexedDB, synchronized, is worth its cost. |
Rollout and verification
- Add the server cart next to the cookie one and read from the server first.
- Write both for one release, then stop writing the cookie cart.
- Measure the request header size of an image request before and after.
The 2 a.m. failure
Support reports that some customers' carts stop updating and that a few get signed out. A cart that grows past the cookie limit produces a Set-Cookie that the browser may refuse to store (the exact behaviour differs between browsers), and an oversized Cookie header on every request can be rejected by a proxy in front of the shop (illustrative). The customer sees an old cart or a sudden sign-out because the session cookie shares the same header.
First three checks: (1) look at the size of the Cookie header on a failing request; (2) look at the response to the request that tried to set the cart cookie; (3) check whether the failure appears only for large carts. Mitigation: stop writing the cart to the cookie and serve it from the server cart. Follow-up: alert on header size, and add a test that fails when any cookie the app sets grows past a budget.
Architect's notes
- Name the need before the store: size, lifetime, who reads it, whether the server or a worker needs it.
- Cookies are for what the server must receive. Everything else stays in the browser.
- Treat every store as a cache you may lose.
- Security has its own lesson. Anything script can read, injected script can read too. Choose the place for a credential with Token Storage and Secure Cookies, and see XSS Defenses.
The other side of this topic
On the server side, the counterpart of "where does this state live" is whether a service keeps per-user state at all: the back-end lessons on stateless services and on Redis data structures cover where session and cart state go when the browser holds only an id.
Common mistakes
- Using a cookie as general storage. The browser sends it with every matching request, and it is capped at about 4 KB.
- Reaching for
localStoragefor everything. It is synchronous, strings only and invisible to workers. - Storing large or structured data in Web Storage. Blocking calls and
JSON.stringifylosses are the price. - Assuming data stays. Best-effort storage can be evicted, and a user can clear it.
Key takeaways
- Every store is a set of constraints: what it holds, sync or async, sent or not, workers or not, lifetime and scope.
- Only cookies are attached to requests by the browser, so they suit what the server must see and nothing else.
- Web Storage is synchronous, string-only and per origin (
sessionStoragealso per tab). IndexedDB and the Cache API are asynchronous and available in workers. - Quotas for IndexedDB and the Cache API are browser-defined, and data is best-effort unless persistence is granted.
- Pick the smallest scope that meets the need, and treat stored data as a cache.
Practice exercises
Exercise 1 — Starter (45 min): List every piece of data your app keeps in a browser store. For each, write the five needs (size, lifetime, server, worker, blocking) and check the store against the table.
Exercise 2 — Intermediate (2 hours): In the lab, add a need for a feature flag set that the server also reads, and decide which store the lab should prefer. Add a test.
Exercise 3 — Advanced (half day): Total the Cookie header size of every request one page of your app makes, and write down which cookies could be removed or moved.
Related reading
In this course:
- Token Storage and Secure Cookies, the security view of the same choice.
- State Persistence and Synchronization, versioning, quota errors and tabs.
- HTTP Caching and Caching Across the Stack, where the Cache API sits next to the HTTP cache.
- Web Workers and Offloading, what a worker can reach.
Planned lessons in this course go deeper on cookies and Web Storage, and on IndexedDB and storage quotas; they are named here in plain text because they are written at the same time as this one.
Official documentation
- MDN: Storage quotas and eviction criteria, what counts against a quota, best-effort and persistent storage, eviction.
- MDN: Web Storage API and Using the Web Storage API, scope, strings and synchronous behaviour.
- MDN: Using HTTP cookies, cookies versus storage APIs.
- MDN: IndexedDB API and Cache.
- MDN: Functions and classes available to Web Workers.
- RFC 6265: HTTP State Management Mechanism, section 6.1 on limits.