Skip to content

fix(hydrogen): stop showing a failed cart read as an empty cart - #4374

Open
andguy95 wants to merge 1 commit into
mainfrom
an-cart-load-error
Open

andguy95 wants to merge 1 commit into
mainfrom
an-cart-load-error

Conversation

@andguy95

@andguy95 andguy95 commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

TL;DR: When the server can't read the cart, for example when the Storefront API throttles the cart query, shoppers saw an empty cart with no checkout button even though their cart still existed. The cart state now reports the failure as loadError, and the template shows "We couldn't load your cart." with a Try again button.

When the cart query returns GraphQL errors, getCart returns {cart: null, errors} and the cart GET handler passes both to the root loader. createCartStore only read cart, so it treated the failed read as "this shopper has no cart". It settled with loading: false and empty data, and it never loaded the cart in the browser, because initial data means the server already answered. The shopper's cart and cookie were fine, but the drawer said "Your cart is empty." until the next cart change or refresh(). Streamed initialData dropped the errors the same way.

I chose an explicit error state over two alternatives. Throwing from the loader would turn every page into the error page whenever the cart read fails. Retrying in the browser on its own hides the failure from the shopper, and for streamed data it would start a fetch during server rendering.

Before

const store = createCartStore({
  initialData: { cart: null, errors: [{ message: "Throttled" }] },
});

store.getState();
// { loading: false, data: <empty cart>, ... }
// The drawer renders "Your cart is empty."

After

store.getState();
// { loading: false, data: <empty cart>, loadError: { message: "Throttled" }, ... }
const loadError = useCart((state) => state.loadError);
const { refresh } = useCartActions();

if (loadError) return <button onClick={refresh}>Try again</button>;
03-drawer-failed 04-drawer-retrying

What this changes

  • loadError on the cart state. The store sets it when resolved or streamed initialData has a null cart with errors. It also sets it when a full load fails before the store has a cart ID, which covers the first load without initial data and the load after reset(). It's a CartNetworkEntry, so a non-2xx response keeps its status.
  • refresh() is the retry. The store never retries on its own. A retry that returns the cart, or confirms there is no cart, clears loadError. A retry that fails replaces it and adds no second network error. reset() from the failed state reloads the cart.
  • Cart changes don't clear loadError. An add from the failed state merges only the added line, so data can hold a partial cart until a full load.
  • Browser cart loads read errors. A {cart: null, errors} response from your cart endpoint now counts as a failed load instead of "no cart".
  • Cart analytics baseline. trackCartAnalytics now updates its baseline when the cart changes without a new updatedAt. Without this, a retry that loads the full cart after an add would make the next change report every existing line as added.
  • Logging. The store doesn't log failed reads that the cart handler already logged on the server. Other load failures still log.

Developer impact

Includes a minor changeset for @shopify/hydrogen. Adds the optional CartState.loadError field. Storefronts that don't read it still show an empty cart after a failed read, as before.

Other behavior changes:

  • store.fetch() now rejects when your cart endpoint returns {cart: null, errors}.
  • A failed first load, or a failed load after reset(), now sets loadError instead of leaving a plain empty state.
  • Without a configured cart endpoint or a cart provider, cart loads go through Standard Actions, where a failed read still looks like no cart.

Docs: TSDoc for CartState, CreateCartStoreOptions, CartStore.fetch() and CartStore.refresh(), the hydrogen-cart-ui skill (SKILL.md, references/react.md, references/vue.md), and the cart notes in the 2026-10 migration guide. The TSDoc examples now pass the handler's data envelope instead of { cart: loaderData.cart }, which dropped errors.

UX impact

In the React Router template, while loadError is set:

  • The cart drawer and /cart show "We couldn't load your cart." with a Try again button. After an add from this state, the message reads "Your item was added, but we couldn't load the rest of your cart."
  • While the retry runs, the message reads "Loading your cart…" in a polite live region. The button stays in place and ignores clicks until the retry finishes.
  • Lines, totals, Shop Pay, Checkout, and item counts are hidden. The header cart link is labelled "Cart" with no count, and the drawer's status region doesn't announce "Cart totals updated".
  • The template doesn't publish CART_VIEWED.

Out of scope

  • The hydrogen, Nuxt, and Next.js examples still show an empty cart when loadError is set.
  • Try again on /cart needs JavaScript.
  • After a successful retry, focus doesn't move to the cart heading.
  • Two edge cases this PR leaves as they are: overlapping adds from the failed state can still report existing lines as added, and reset() before connect() or during a refresh leaves the cart loading.

Risk

  • trackCartAnalytics changes for every storefront, not only in the failed state. A cart that changes without a new updatedAt now replaces the baseline without publishing events.
  • store.fetch() rejecting for a failed read is new. Code that awaits it now sees the error.

How to Test

  1. Run pnpm install, then pnpm turbo run build --filter='@shopify/hydrogen-template-react-router^...'.
  2. Run pnpm --filter @shopify/hydrogen-template-react-router dev and open the URL Vite prints. Add a product, then open the cart drawer to confirm it's there.
  3. In templates/react-router/app/root.tsx, temporarily change the loader's cartData: cartResult.data, to cartData: { cart: null, errors: [{ message: "Throttled" }] }, and reload.
  4. Confirm the header cart icon shows no count, and the drawer shows "We couldn't load your cart." with Try again and no total or Checkout.
  5. In DevTools > Network, block requests to /api/cart and click Try again. Confirm "Loading your cart…" appears, then the error again.
  6. Unblock /api/cart and click Try again. Confirm the cart from step 2 appears with its total and Checkout, and the header count comes back.
  7. Open /cart and confirm the same failed state. Revert the loader change.

I ran this flow in headless Chromium with Playwright against mock.shop. In that run, the failed retry in step 5 came from a route override that answered /api/cart with {cart: null, errors}, not from a blocked request.

When the cart query returns errors, the cart GET handler returns
{cart: null, errors}. The cart store ignored the errors and showed an
empty cart with no browser load. The store now sets CartState.loadError
for resolved and streamed initial data, and for a full load that fails
before the store has a cart ID. refresh() is the retry. The React Router
template shows a "couldn't load your cart" message with Try again and
hides the cart's lines, totals, and counts while loadError is set.

trackCartAnalytics now updates its baseline when the cart changes
without a new updatedAt, so a retry after an add doesn't make the next
change report existing lines as added.
@shopify

shopify Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Oxygen deployed a preview of your an-cart-load-error branch. Details:

Storefront Status Preview link Deployment details Last update (UTC)
Skeleton (skeleton.hydrogen.shop) ✅ Successful (Logs) Preview deployment Inspect deployment November 13, 202612:43 AM

Learn more about Hydrogen's GitHub integration.

@andguy95
andguy95 marked this pull request as ready for review November 13, 2026 00:53
@andguy95
andguy95 requested a review from a team as a code owner November 13, 2026 00:53
@andguy95
andguy95 requested a review from fredericoo November 13, 2026 00:53
@fredericoo

fredericoo commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

thanks for digging into this, the diagnosis is spot on and the test coverage is solid. i'd like to hold off on merging this shape though, and go with a different API that we can ship additively in a minor

my worry with loadError is that it's easy to hold wrong. data still holds an empty (or partial) cart while loadError is set, so any useCart((s) => s.data.totalQuantity) that doesn't check loadError first quietly brings back the "Your cart is empty" bug, and TS won't flag it. the template diff shows this: Header, the drawer lines, footer, status region, /cart and CART_VIEWED all needed their own hasLoadError check. it also stacks a third flag on top of loading and revalidating, so we get combinations that don't make sense

what i'd rather do is pull the load lifecycle out of useCart entirely:

useCart(sel)       // unchanged: data is always there. loading and readyPromise get deprecated
useCartStatus()    // the only place the lifecycle lives:
  | { phase: 'loading' }
  | { phase: 'ready' }   // includes "no cart" (data.id === null)
  | { phase: 'failed'; error: CartNetworkEntry; retrying: boolean; retry(): void }

plus a <CartReady> wrapper that only renders its children once the cart is ready:

<CartReady
  loading={<p>Loading cart…</p>}
  failed={({ retry, retrying }) => <CartLoadError onRetry={retry} busy={retrying} />}
>
  <CartLines />
  <CartFooter />
</CartReady>

(phase rather than status so it doesn't clash with error.status)

what this gets us:

  • the six hasLoadError checks become one wrapper. CartLines goes back to "empty or not", and CartFooter and the CART_VIEWED effect need no check since they sit inside it
  • the header badge becomes <CartReady loading={null} failed={null}><CartCountBadge /></CartReady>
  • every pending / errors / revalidating read stays as it is today
  • no error boundaries needed: <CartReady> reads useCartStatus() and picks what to render, so it works the same in Vue and Solid (named slots there)
  • data is always a valid object, so if the phase flips while children are still mounted they read an empty cart for one render rather than crashing

a few rules i think it needs:

  • refresh() from failed stays failed with retrying: true until the load settles, so the error UI doesn't flicker
  • a successful cart change from failed triggers a background reload, and only that reload moves it to ready. this avoids depending on the mutation response being the full cart, since mergeAddResponseLines only merges the matched lines
  • reset() from failed reloads the cart, same as here
  • in React, <CartReady> should suspend on the store's ready promise while loading, rather than render the loading slot, so streamed initialData still gets the cart into the SSR stream. the promise moves off CartState and becomes internal (something like store.ready())

with this i think useSuspenseCart could be deprecated, since <CartReady> covers it. the trade-off is that useCart outside a <CartReady> still shows an empty cart when the read fails, so the template, the hydrogen-cart-ui skill and the migration guide should make the wrapper the default

none of this needs to break anyone:

  • storefronts that don't adopt <CartReady> keep today's behaviour
  • loading, readyPromise and useSuspenseCart keep working, with deprecation notices
  • store.fetch() and errors.network keep their current semantics, so let's not make fetch() reject on {cart: null, errors}
  • the trackCartAnalytics baseline fix from this PR is still needed for the background reload

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants