What you'll learn: By the end of this lesson you will be able to decide which state is worth saving and where to save it, explain what turning state into a string keeps and loses, load saved data defensively (version, migrate, discard what is corrupt), handle a full or unavailable storage, cut writes with a debounce, explain how the
storageevent reaches other tabs, and say why synchronizing tabs means choosing who wins when two writers disagree.
Think of a shopping list on the fridge. You can leave it there, and when you come back it is still there: that is persistence. But the list may be an older version in a format you no longer use, someone may have spilled coffee on it, and your flatmate may have added "milk" while you added "eggs" on a second copy. Reading it back is an act of trust, and keeping two copies agreeing is a separate problem: synchronization.
The running example is a cart plus a theme preference on a shop. Reloading the page, closing and reopening the tab, and having the shop open in two tabs at once should all behave sensibly. The lab's cart is made up for the lesson.
The core idea
- Persisting state is serialize, store, read back, and the read is untrusted. The string in storage may come from an older build, a newer build, another tab, a failed write or a user with developer tools. Treat it like input from the network.
- Choose the store by what it holds and how it is read. Small strings that are cheap to read go in Web Storage. Large structured data goes in IndexedDB. Data that other people must see belongs on a server.
- Synchronization is a decision about who wins. When two holders of the same state change it at the same time, something must order their writes, and ordering is not merging: a rule that picks a winner discards the loser's change.
Three illustrations run through the lesson: a minimal example (a cart round trip through JSON), a realistic example (the cart and theme with versions and two tabs) and a failure example (an old saved cart that crashes the new release).
What to save, and where
Not all state deserves saving. A draft, a cart and a theme do. Search results, a server cache, a loading flag or a value derivable from other state should be rebuilt. Libraries expose the same idea: Zustand's persist middleware has a partialize option, "a function to filter state fields before persisting it", and the lab's partialize does the same.
| Place | What it holds | Scope and lifetime | Reads and writes | Fits |
|---|---|---|---|---|
sessionStorage |
Key/value pairs | Per tab and origin; destroyed when the tab closes | Synchronous | Per-tab drafts, wizard progress |
localStorage |
Key/value pairs | Per origin; survives closing the browser | Synchronous | Preferences, a small cart |
| IndexedDB | Objects (anything the structured clone algorithm supports), files and blobs | Per origin | Asynchronous, transactional | Large or structured data, offline data |
| The server | Anything | Shared by all your devices | Network calls | Data of record, multi-device state |
MDN states that both Web Storage areas are synchronous: a read or write blocks other JavaScript until it finishes. That is a reason to write rarely and keep values small. Storage only supports strings, so objects must be converted, for example with JSON.stringify(). IndexedDB is described as a low-level API for client-side storage of significant amounts of structured data. It is transactional, asynchronous and follows the same-origin policy. The course plans separate lessons on each store.
Turning state into a string
Figure 1. The save path and the load path
How to read this: the top path writes, the bottom path reads. The step in the middle of each is where problems are caught: serialization can fail or lose data, and loading must check what it got.
JSON.stringify is the usual serializer, and it is lossy. MDN documents that undefined, functions and symbols are omitted from objects, Date objects become ISO strings through toJSON(), a Map or Set becomes {}, NaN and Infinity become null, and a circular reference throws a TypeError. After a round trip a Date is a string and a Set is an empty object. The lab's first section prints exactly this. IndexedDB uses the structured clone algorithm instead, which supports Date, Map and Set but cannot copy functions: attempting it throws a DataCloneError.
The practical rule: persist plain data (strings, numbers, booleans, arrays, plain objects), and convert anything richer on the way in and out.
Loading defensively
A loader that does JSON.parse(localStorage.getItem(key)) and uses the result will fail on the first bad string. The lab's loader returns a state and a status instead, and never throws on data:
| Status | What it means | What the loader does |
|---|---|---|
empty |
Nothing saved | Starts from the initial state |
restored |
Saved with this version | Merges saved data over the initial state, so fields added later get defaults |
migrated |
Saved by an older version | Runs a migrate function, then merges |
outdated |
Older, and no migrate |
Ignores it |
newer-version |
Written by a newer build (for example after a rollback) | Ignores it and leaves the stored value alone |
corrupt |
Not JSON, or the wrong shape | Ignores it |
The envelope that makes this possible wraps the state: { v, rev, writer, state }, a schema version, a revision, the tab that wrote it, and the data. Zustand's persist middleware documents the same ideas: a version for the persisted state ("if the stored state version doesn't match, it won't be used"), a migrate function for a version mismatch, and a merge function that defaults to a shallow merge. createJSONStorage "does not perform any runtime validation", so checking the shape is your job.
Figure 2. Deciding what to do with a saved string
saved?"} N -->|"no"| E["empty: initial state"] N -->|"yes"| P{"Valid JSON and
an envelope?"} P -->|"no"| C["corrupt: initial state"] P -->|"yes"| V{"Version vs
this build"} V -->|"newer"| W["newer-version: ignore,
leave stored value"] V -->|"older"| M{"migrate
exists?"} M -->|"no"| O["outdated: initial state"] M -->|"yes"| G["migrated: merge"] V -->|"same"| S["restored: merge"]
How to read this: every path ends in a usable state. The app always starts, whatever the string contained.
Hydration caveat. Storage does not exist on the server, so an app that reads it during the first render can produce different markup than the server did. Restore after hydration, or use the library's option to skip automatic rehydration (skipHydration in Zustand's persist). See Debugging Hydration Mismatches.
When storage is full or gone
setItem can throw. MDN says QuotaExceededError is thrown if the storage runs out of disk quota or the user declined to grant more space, and the HTML Standard notes that setting could also fail if the user has disabled storage for the site. Browsers manage storage per origin and decide the maximum themselves, so the lesson gives no numbers. By default data is best-effort: it persists while the origin is below its quota and the user does not delete it, and the browser may evict it under pressure. An origin can ask for persistent storage with navigator.storage.persist(), and navigator.storage.estimate() returns an estimate of usage, not the actual value.
For state you can rebuild, the right response to a failed write is to keep working in memory and report the failure. The lab's saveState returns { ok: false, reason: "quota" } and the store keeps the unsaved change marked dirty for the next attempt.
Writing less often
Because Web Storage is synchronous, writing on every change (every keystroke into a draft) blocks the main thread each time. The usual fix is a debounce: save after a quiet period. The lab's store waits debounceMs after the last change, and a flush() writes at once. A real page would call a flush when the page is being hidden or closed, which the lab does not model. See Debouncing and Throttling for the timing rules.
Synchronizing tabs
With localStorage, all documents of one origin share one storage area. MDN describes the storage event as fired when another document that shares the same storage area updates it, and not on the window that made the change. For localStorage it reaches other tabs of the same origin. For sessionStorage it reaches only embedded frames of the same tab.
So a tab can listen for changes and adopt them. Two rules keep it from going wrong:
- Adopt only newer data. Each write carries a revision. A tab adopts an incoming state only if its revision is higher than its own, and adopting does not trigger a write back, or two tabs would echo each other forever.
- Break ties. Two tabs that change at the same moment produce the same revision. Without a tie-break (the lab uses the writer's name) neither adopts the other's and the tabs stay different.
Figure 3. Two tabs change the cart at the same moment
How to read this: the tabs converge, which is good, but one change disappears. Ordering writes is not merging them. Merging needs a data type that can combine concurrent changes, which is the subject of other lessons in this course on cross-tab sync and CRDTs.
Persisted state is also a cache or a draft, not the truth. For anything the user expects on another device, the server holds the data of record and local storage only keeps the user's place.
Choosing
Figure 4. Where should this state go?
cheaply?"} -->|"yes"| X["Do not persist it"] Q -->|"no"| T{"How far must
it travel?"} T -->|"this tab only"| SS["sessionStorage"] T -->|"this device, small"| LS["localStorage
+ version, defensive load"] T -->|"this device, large
or structured"| IDB["IndexedDB"] T -->|"all devices"| SV["Server is the source
of truth"]
How to read this: persist only what hurts to lose, and use the smallest scope that serves the user.
| Choice | Gain | Cost |
|---|---|---|
Persist a small slice (partialize) |
Small, fast, easier to migrate | Some state is rebuilt on load |
| Last writer wins across tabs | Simple, tabs converge | A concurrent change is lost |
| Server as source of truth | All devices agree | Network, auth, conflict handling on the server |
Build it: save, load, migrate, and two tabs
Goal. Run a model of Web Storage and a persisted store through five situations: JSON's losses, loading six kinds of saved string, a full storage, debounced writes and two tabs that change the cart together.
Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It is pure logic: no React, no DOM.
cd examples/frontend
pnpm install
cd labs/state-persistence
pnpm test # 30 tests
node src/demo.ts
Steps.
- Run the tests, then the demo, and compare it with the output below.
- In section 2, find the row "newer build wrote it". The loader returns the initial state but the stored value is untouched, so a rollback does not destroy data that the newer build can still read.
- In section 5, follow the revisions. After both tabs write at revision 2, tab A adopts tab B's state and tab B ignores A's. No further events are delivered, so there is no echo.
Expected output, captured from a real run (Node 26.13.1, 2026-11-30):
State persistence and synchronization: what survives, what breaks, who wins
=== 1. What JSON does to state on the way to a string
saved text: {"count":2,"createdAt":"2026-01-02T03:04:05.000Z","tags":{},"ratio":null}
keys before: count, createdAt, tags, note, undo, ratio
keys after: count, createdAt, tags, ratio
createdAt: string 2026-01-02T03:04:05.000Z (a Date again: false)
tags: {} (the Set's members are gone)
ratio: null (NaN became null)
circular state: {"ok":false,"reason":"unserializable"}
=== 2. Loading: the saved string is not trusted
nothing saved -> empty {"lines":{},"theme":"light"} (stored value untouched: true)
current version -> restored {"lines":{"p1":2},"theme":"dark"} (stored value untouched: true)
current, field missing -> restored {"lines":{"p1":1},"theme":"light"} (stored value untouched: true)
older, with migrate -> migrated {"lines":{"p1":2,"p2":1},"theme":"dark"} (stored value untouched: true)
older, no migrate -> outdated {"lines":{},"theme":"light"} (stored value untouched: true)
newer build wrote it -> newer-version {"lines":{},"theme":"light"} (stored value untouched: true)
not JSON -> corrupt {"lines":{},"theme":"light"} (stored value untouched: true)
JSON, wrong shape -> corrupt {"lines":{},"theme":"light"} (stored value untouched: true)
=== 3. A full storage: report it, keep working in memory
first save: {"ok":true,"chars":88}; storage uses 92 of 150 characters
second save: {"ok":false,"reason":"quota"}; storage still holds the first save: ["cart"]
state in memory still has 30 history entries
with partialize (history not saved): {"ok":true,"chars":75}
=== 4. Debounced writes: many changes, one write
t=100 5 changes made, writes so far: 0, stored: nothing
t=350 after the quiet period, writes: 1, stored: {"v":2,"rev":5,"writer":"tab-1","state":{"lines":{"p1":5},"theme":"light"}}
t=350 one more change, then flush() at once: {"ok":true,"chars":74}, writes: 2
t=1350 the cancelled timer wrote nothing more, writes: 2
=== 5. Two tabs, one storage area: events, adoption and a lost update
A added p1, written: A={"p1":1} (rev 1) B={} (rev 0)
events delivered: 1
after delivery: A={"p1":1} (rev 1) B={"p1":1} (rev 1)
both changed, written: A={"p1":1,"p2":1} (rev 2) B={"p1":1,"p3":1} (rev 2)
events delivered: 2
after delivery: A={"p1":1,"p3":1} (rev 2) B={"p1":1,"p3":1} (rev 2)
stored: rev 2 by tab-B; p2 (from tab-A) is gone from every tab
tab-A: writes 2, adopted 1, ignored 0
tab-B: writes 1, adopted 1, ignored 1
events delivered after that: 0 (no echo)
What the lab does not show. No browser: it never touches window.localStorage, IndexedDB or a real storage event, and the 150-character limit is made up. Real events are delivered as tasks, which the model imitates by delivering them when asked. Flushing on page hide, and the tab-ordering rule, are this lab's own design choices and not how any library works.
Break it. In src/persistedStore.ts, change the body of newer to return a.rev > b.rev;. Concurrent tabs now have equal revisions, neither adopts the other's state, and "converges after concurrent changes" fails. Revert it.
In practice: a release that crashed for returning shoppers
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 saves its cart to localStorage as a plain JSON array of product ids and restores it on start-up with JSON.parse and no checks. A release changes the cart to a map of quantities by id. New visitors are fine. Returning visitors still have the old array saved.
Starting architecture
Figure 5. Starting point: the loader trusts the string
How to read this: nothing between storage and the new build asks "which version wrote this?".
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Change the key name for the new shape | New and old data never meet | Returning users lose their cart | Old keys pile up unless cleaned |
| Version the envelope, migrate old data, ignore what is invalid | Returning users keep their cart; bad data cannot crash start-up | A migration function and fixtures to test | Migrations accumulate over time |
The decision
| Field | Decision record |
|---|---|
| Context | A new release reads data written by older releases, and the loader trusts it. |
| Decision | Wrap the cart in a { v, rev, writer, state } envelope. Add a migration from the unversioned array. Load defensively: any failure starts from the initial state. Keep the old value untouched when it is from a newer version. |
| Consequences, good | Returning shoppers keep their carts, a rollback does not destroy data, and corrupt data cannot stop the app starting. |
| Consequences, bad | Each schema change needs a migration and a test fixture. |
| Revisit when | The saved state grows beyond a small cart (consider IndexedDB), or the cart must follow users across devices (move it to the server). |
Rollout and verification
- Write fixtures for every shape a user can have: nothing, the old array, the new map, invalid JSON.
- Ship the loader first with the migration, and watch the status counts (
restored,migrated,corrupt). - Add the new write path once the loader is live, so a rollback can still read what is saved.
The 2 a.m. failure
After the release, support reports a blank page for some returning shoppers, and refreshing does not help. Error tracking shows a TypeError on the first render for users whose saved cart is the old array, because the code reads .lines of an array and the state was never validated (illustrative). The bad string stays in storage, so every reload fails the same way.
First three checks: (1) reproduce with an old saved value in storage; (2) check whether start-up reads storage unguarded; (3) check whether anything clears or replaces the bad value. Mitigation: ship a loader that treats any parse or shape failure as corrupt and starts from the initial state, and write the cleaned state on the next change. Follow-up: add the fixtures above to the test suite, count load statuses in monitoring, and review every persisted shape change for a version bump.
Architect's notes
- Persist the minimum. Choose fields on purpose, and rebuild the rest.
- Version every persisted shape from day one. Adding a version later means guessing what old data looked like.
- Make loading total. Any string, including a corrupt one, must end in a working state.
- Order writes with a revision, merge with a data type. Decide which your feature needs, and say so in the design.
Common mistakes
- Parsing without a try/catch, or without checking the shape.
- No version in the saved data, so a changed shape breaks returning users.
- Writing on every keystroke into a synchronous store.
- Persisting derived or server data, so the saved copy goes stale.
- Rebroadcasting what you just received, causing an echo between tabs.
Key takeaways
- Persisting is serialize, store, read back, and the read is untrusted input.
JSON.stringifydrops functions andundefined, turnsDateinto a string andMap/Setinto{}. Persist plain data.- Web Storage is synchronous and string-only; IndexedDB is asynchronous and stores structured data. Writes can throw
QuotaExceededError. - Version the envelope, migrate older data, ignore newer or corrupt data, and merge with defaults.
- Debounce writes and flush when the page is leaving.
- The
storageevent reaches other documents, not the writer. Adopt only newer revisions, break ties, and never write back what you adopted. - Ordering is not merging: last writer wins loses a concurrent change.
Practice exercises
Exercise 1 — Starter (45 min): Find one JSON.parse(localStorage.getItem(...)) in your code or a sample app. Write the six fixtures from the loading table, and make the loader pass all of them.
Exercise 2 — Intermediate (2 hours): In the lab, add a version 3 whose cart stores { productId, quantity } objects, write the migration from version 2, and add tests with the saved strings of versions 1 and 2.
Exercise 3 — Advanced (half day): Replace the last-writer-wins rule with a merge that takes the larger quantity per product. Write one test it passes (two different products) and one it cannot pass (a removal in one tab, an increase in the other), and explain why.
Related reading
In this course:
- Local vs Global State in the Front End, what lives where and for how long, before any of it is saved.
- Debugging Hydration Mismatches, why server and client must agree on the first render.
- Debouncing and Throttling, the timing rules behind a quiet-period save.
- Caching Across the Stack: Browser, CDN, Server and Client State, where persisted client state sits among the other caches.
Official documentation
- MDN: Web Storage API, Storage.setItem() and Window: storage event.
- WHATWG HTML: Web storage, the
setItemsteps and the broadcast to other windows. - MDN: IndexedDB API and Storage quotas and eviction criteria.
- MDN: JSON.stringify() and The structured clone algorithm.
- Zustand: persist middleware,
version,migrate,partialize,mergeandskipHydration.