Your Cart Is a Distributed System (And That's Why It Desyncs)
The short answer: A cart that lives in a client store, a server API, localStorage and multiple tabs is a distributed system, and it suffers the same problems: stale reads, conflicting writes and lost updates. The fix is to make synchronization explicit — rebase client state from server responses at defined points, store the cart token with the data, listen for cross-tab storage events and rehydrate, and reconcile variations by identity rather than index.
The bug reports all sounded different: "my cart emptied after login," "I added two variants but see one line," "the other tab still shows the old cart." They were the same bug wearing different clothes — a state machine with four copies and no agreed authority.
1. Four copies of one truth
A typical cart has:
- A client store (Zustand or similar) driving the UI.
- A server cart (WooCommerce or a custom API) holding the real line items.
- A persisted copy in localStorage for reload survival.
- An auth token that changes the server's view of the cart when the user logs in.
Every copy can be correct at one instant and wrong the next. Without explicit synchronization, the last write wins — and "last" is not well defined across tabs and network delays.
2. Rebase on the server response
Mutations should be optimistic for responsiveness, but they must be followed by a reconciliation step: replace local state with the server's authoritative response. Otherwise a quantity clamp, a coupon rejection or a stock limit applied server-side is invisible to the UI.
const serverCart = await updateCartAction(lineItems);
setCart(reconcile(localCart, serverCart)); // derive from truthThe important shift is from "apply my change and hope" to "apply my change, then converge on what the server says."
3. Variations must be matched by identity
A recurring source of duplicate or merged lines is matching on product ID alone. Two variations of the same product are different lines. Reconciliation must match on full identity — product plus variation attributes — and merge by quantity only for exact matches.
This is a data-modeling rule, not a UI detail: if your cart item type cannot express variation identity, every later fix will be a patch on a broken foundation.
4. Cross-tab sync is not automatic
Each tab has its own in-memory store. localStorage is shared, but a tab does not re-read it just because another tab wrote it. Listen for storage events and rehydrate:
if (typeof window !== 'undefined') {
window.addEventListener('storage', (e) => {
if (e.key === 'cart-storage') useCartStore.persist.rehydrate();
});
}Now a change in one tab propagates to the others. Without this, the "two tabs disagree" report is inevitable.
5. Persist only what matters
State stores accumulate transient flags: loading, open/closed drawers, error messages. Persisting all of them means a reload can restore a stale error or a stuck spinner. Use partialize to persist only the cart items and the cart token:
persist(
(set, get) => ({ ...state }),
{
name: 'cart-storage',
partialize: (state) => ({
items: state.items,
cartToken: state.cartToken,
}),
}
)The token must be persisted with the items: a cart without its token is a cart the server cannot identify.
6. Auth transitions are synchronization points
Login and logout change the server's view of the cart. These are explicit synchronization points: refetch the server cart and replace local state after the auth state changes. Treating them as ordinary background events is how carts appear to "empty after login."
7. Defense in depth
| Problem | Naive approach | Explicit sync |
|---|---|---|
| Server clamps quantity | Local optimistic value sticks | Rebase on server response |
| Two tabs | Each keeps own state | Storage event + rehydrate |
| Variations | Match by product ID | Match by full identity |
| Reload | Restores transient UI state | Persist only items + token |
| Login | Cart seems to empty | Refetch at auth transition |
How to fix cart desync
- Define which copy of the cart is authoritative at each point.
- Rebase local state on server responses after every mutation.
- Match line items by product plus variation identity.
- Listen for storage events and rehydrate across tabs.
- Persist only items and token; refetch on auth transitions.
Frequently asked questions
Is the server or the client authoritative? The server, for anything that affects price, stock or orders. The client is an optimistic projection of it.
Do storage events fire in the same tab? No — they fire in other tabs of the same origin. Same-tab updates must go through the store directly.
Should I persist the whole store? No. Persist data, not UI state. Use partialize.
What about offline support? Offline queues need their own versioning and conflict resolution; start with explicit server rebasing before adding offline complexity.
Key takeaways
- Carts are distributed state; treat them that way.
- Rebase on the server after mutations.
- Match variations by full identity.
- Sync tabs via storage events and rehydration.
- Persist only items and token; refetch on auth changes.
Summary
Most cart bugs are not UI bugs — they are consistency bugs. Once you name the authority and define the synchronization points, the mysterious desyncs become deterministic behavior you can reason about.
References
- Zustand documentation — persist middleware and partialize.
- MDN Web Docs — StorageEvent.
- React documentation — useSyncExternalStore.