Skip to content

fix(hydrogen): read the cart only on /cart, and keep changes made during the first load - #4385

Open
andguy95 wants to merge 10 commits into
an-cart-privatefrom
an-cart-await-first-load
Open

andguy95 wants to merge 10 commits into
an-cart-privatefrom
an-cart-await-first-load

Conversation

@andguy95

@andguy95 andguy95 commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #4344. Follows up on the part 2 review comment.

TL;DR: #4344 marks every cart read as personalized, so a root loader that reads the cart makes every route's response private. This moves the template's server cart read to the /cart route. Other pages then load the cart in the browser, which exposes a store bug: a change made during that first load built on an empty cart. The store now waits for the first load before sending the change, and replays the change on top of the loaded cart.

Before

Measured in Chromium against the template on mock.shop (its default .env). The template reads the cart only on /cart, the store is unchanged, and the cart already has 3 items. The first GET /api/cart is slowed by 3s, the add by 2s, and the buyer clicks Add to cart during the load:

  • The badge and drawer show Cart (1 item) for 2.3s, and the drawer reports the cart as done loading.
  • The add's POST goes out right away. The first GET lands afterwards and is thrown away, so the store fetches the cart a second time.
  • The stock-limit rollback E2E fails with Expected 49, Received 1, whether or not the test holds the first read.

Any storefront that loads the cart in the browser has this today. The template doesn't, only because its root loader reads the cart on every page.

After

Same setup:

  • The badge shows Cart (1 item) for 2.4s, and the drawer shows the line with "Loading the rest of your cart…" under it.
  • The POST is sent 17ms after the first GET lands. The badge goes to 4 when the load lands, and there's no second fetch.
  • The cart E2E spec passes 5/5.

What this changes

  • Cart store (packages/hydrogen/src/core/cart/cart.ts): a change made during the first load shows at once. Its request waits until the load lands, returns no cart, or fails. The load is no longer cancelled by the change, so loading and readyPromise keep describing it.
  • Template and examples/hydrogen: cartHandlers.get moves from the root loader to the cart route's loader. The root CartProvider seeds from useRouteLoaderData("routes/cart") when that route is rendered, and loads in the browser everywhere else.
  • Cart drawer and the example's cart aside: during the first load they show "Loading cart…" instead of the empty-cart message. Lines added during the load stay visible, with a note that the rest of the cart is still loading.
  • Nuxt example: useServerRenderedCart marks the page's own request context personalized. useFetch("/api/cart") runs as a separate request, so the cart handler's mark never reached the page.
  • Storefront E2E: the stock-limit test holds only the POST and lets the first cart read through. The contract now requires a server-rendered cart only on the cart page, and says a change made during the first load must build on the loaded cart.

Developer impact

Includes a patch changeset for @shopify/hydrogen. It's a bug fix in the cart store, and no exports change. The hydrogen-cart-ui, hydrogen-setup, and migrate-to-hydrogen-2026-10 skills now teach reading the cart in the cart route's loader instead of the root loader. The old pattern still works, but it marks every response personalized.

Behavior changes worth knowing:

  • A promise initialData that hasn't settled after 30s counts as a failed load, so held changes are sent.
  • A change sent from code with window.Shopify.actions.updateCart during the first load is already on the network. It can't be held, so it still ends the load and refreshes the cart.

UX impact

  • Outside /cart, the HTML no longer contains the cart. The header badge fills in after hydration and the first GET /api/cart. Without JavaScript, the badge shows no count outside /cart.
  • During the first load, the header badge shows only the changes made so far (Cart (1 item) when the cart really has 3). The drawer marks this as loading, but the header and its screen-reader live region don't.
  • Both apps open the cart drawer from the product form's afterSubmit, which runs once the add's request lands. During a slow first load, that request waits for the load, so the drawer opens later than it did before.

Out of scope

  • A loading state for the header badge and its live region.
  • Full HTML pages stay private. The CSP nonce makes every document response private (packages/hydrogen/src/core/csp/index.ts:68). The win here is navigation data: on the template dev server, /collections.data went from private to no Cache-Control, and /cart.data stays private.
  • A client-side navigation to /cart still runs the cart route's loader, so the server reads the cart even though the browser already has it.
  • A discount code applied during the first load still replaces the codes the loaded cart had, as before.

Risk

  • Every change made during the first load now waits for that load, so its server round trip starts later by however long the load takes.
  • cart.ts changes how the store dispatches changes. It deserves the most review attention.

How to Test

  1. Run pnpm install && pnpm build:pkgs.
  2. Run pnpm --filter @shopify/hydrogen-template-react-router exec vite dev --port 4201. The template's default .env runs on mock.shop, so no store credentials are needed.
  3. Open a product page and add the product 3 times, so the cart has 3.
  4. In Chrome DevTools, open the Network tab and set throttling to "Slow 4G".
  5. Reload the product page and click Add to cart right away, then open the cart drawer.
  6. Confirm the drawer shows the line with "Loading the rest of your cart…", then settles at 4.
  7. Reload, and confirm the cart still has 4.

@andguy95
andguy95 requested a review from fredericoo November 17, 2026 03:17
@andguy95

Copy link
Copy Markdown
Collaborator Author

@Freddie one gap I'd love your take on, the header badge only reads totalQuantity, so it still shows 1 during the load with no loading hint, and the live region announces "1 item in cart". I was thinking that we just don't show the badge till loading is complete.

Also flagging just in case: full HTML responses stay private either way because of the CSP nonce, so the cacheable win here is the .data responses (/collections.data is no longer private, /cart.data still is).

@andguy95
andguy95 marked this pull request as ready for review November 17, 2026 03:24
@andguy95
andguy95 requested a review from a team as a code owner November 17, 2026 03:24
@andguy95
andguy95 added this pull request to stack #4388 November 17, 2026 18:32
@shopify

shopify Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

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

Storefront Status Preview link Deployment details Last update (UTC)
Skeleton (skeleton.hydrogen.shop) ✅ Successful (Logs) Preview deployment Inspect deployment November 19, 2026 9:11 PM

Learn more about Hydrogen's GitHub integration.

<HydrogenAnalyticsProvider>
<LocaleProvider locale={data.locale}>
<CartProvider initialData={data.cartData}>
<CartProvider initialData={cartRoute?.cartData}>

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

non-blocking: Could we bring the Hydrogen example’s CartMain into parity with the React Router template’s loading behavior? It currently shows “Looks like you haven't added anything yet” while the cart is still loading, even when the buyer already has items.

@andguy95
andguy95 marked this pull request as draft November 17, 2026 22:34
@andguy95
andguy95 marked this pull request as ready for review November 17, 2026 22:50
@andguy95
andguy95 force-pushed the an-cart-await-first-load branch from f88b419 to c576582 Compare November 18, 2026 21:49
@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

📦 Bundle size report

Status Target Scenario Minified Gzip Δ Minified Δ Gzip
🟡 server entry: @shopify/hydrogen 169.29 kB 53.6 kB -241 B (-0.1%) +4 B (+0.0%)
🟢 client entry: @shopify/hydrogen/react 97.94 kB 31.88 kB -242 B (-0.2%) ±0
🟡 client entry: @shopify/hydrogen/vue 97.75 kB 31.7 kB -242 B (-0.2%) +10 B (+0.0%)
🟢 client react cart 48.06 kB 15.07 kB -242 B (-0.5%) -7 B (-0.0%)
🟢 client vanilla cart 37.2 kB 11.58 kB -241 B (-0.6%) -6 B (-0.1%)
Unchanged (10)
Status Target Scenario Minified Gzip Δ Minified Δ Gzip
⚪ server cart handlers 23.9 kB 7.14 kB ±0 ±0
⚪ server customer account 22.91 kB 7.17 kB ±0 ±0
⚪ server entry: @shopify/hydrogen/customer-account 25.41 kB 8.29 kB ±0 ±0
⚪ server predictive search handlers 9.32 kB 3.71 kB ±0 ±0
⚪ server request handling 53.8 kB 17.52 kB ±0 ±0
⚪ client react collection 11.59 kB 3.94 kB ±0 ±0
⚪ client react predictive search 9.39 kB 3.43 kB ±0 ±0
⚪ client react product 14.66 kB 5.23 kB ±0 ±0
⚪ client react shop pay button 10.13 kB 4.45 kB ±0 ±0
⚪ client react shopify scripts 18.66 kB 6.87 kB ±0 ±0
How this is measured

Each scenario is bundled from the built package with Rolldown (tree-shaken, minified, dynamic imports inlined), then gzipped. Peer dependencies are external. Scenarios live in scripts/bundle-size-scenarios.ts.

🟢 smaller · 🟡 larger (< 5%) · 🔴 larger (≥ 5%) · 🆕 not in base · ❌ failed to bundle · ⚪ unchanged

@andguy95
andguy95 marked this pull request as draft November 19, 2026 18:28
@andguy95
andguy95 marked this pull request as ready for review November 19, 2026 19:45
@andguy95
andguy95 force-pushed the an-cart-await-first-load branch from 1059c85 to 7f977e2 Compare November 19, 2026 19:46
…rsonalized

useFetch runs /api/cart as its own request with its own request context, so neither the cart route's private headers nor the cart handler's mark reach the page that embeds the result. Mark the page's own request context, including for an empty cart.
A change made while the store loads the cart in the browser used to drop the load and build on an empty cart. The change now shows at once, its request waits until the load lands, returns no cart, or fails, and then it replays on top of the loaded cart. A change sent from code with window.Shopify.actions.updateCart is already on the network, so it still ends the load and refreshes.
A storefront may load the cart in the browser. Holding that first read hides the line already at the stock limit, so the test now holds only the change and the contract no longer requires a server-rendered cart outside the cart page.
Reading the cart in the root loader marked every route's response personalized. Only the cart route reads it on the server now, and the root CartProvider seeds from that route's data when it is present. The drawer keeps showing lines during the first load with a note that the rest of the cart is loading.
Outside /cart the cart loads in the browser, so the aside showed the empty-cart message until the first load landed. Show "Loading cart…" instead, and a note under lines added during the load, matching the template drawer.
…s held behind the first load

- Publish the loaded cart on its own before held changes show on it, so the
  analytics tracker diffs the add against the loaded cart instead of null.
- Drop a held change that a newer change replaces at once, so it doesn't
  count as a request in flight (spurious revalidation, hydrate() ignored).
- Re-run a revalidation that a newly adopted cart made stale, so
  revalidating doesn't stay true.
- Hold every change behind the add that creates the cart.
- Stop naming a replaced placeholder line as pending.
- Assert the payload of the held add in the external-change test.
…confirmed lines

- Template header: no count or live-region announcement until the first load
  lands, then announce only changes. The drawer badge waits too.
- Template, Hydrogen, SvelteKit and SolidStart cart lines: disable quantity
  and remove controls for optimistic: lines, which have no server ID yet.
- SvelteKit and SolidStart: show lines added during the load with a note
  instead of the skeleton.
- Hydrogen example: move cart/:lines out from under the cart route, so it
  doesn't run the cart loader before redirecting.
- Stock-limit E2E: hold the first cart read until after the click, so the
  add always starts during the load.
- Skills and changeset: fix the Vue personalized-mark rule and the markets
  root-loader snippet, and document the loading and placeholder rules.
- Publish the analytics baseline only when a cart is adopted, so a load that
  finds no cart or a change that ends the load never publishes an idle state.
- Cancel a revalidation that an adopted cart supersedes instead of rerunning
  it, unless one was requested since.
- Template header: announce a change made during the first load once the
  load lands.
- SolidStart and SvelteKit headers hide the count during the first load;
  Next.js and Nuxt lines lock their controls while unconfirmed.
- Markets skill: use the locale-prefixed cart route ID.
- Stock-limit E2E: hold only the product page's own first cart read.
@andguy95
andguy95 force-pushed the an-cart-await-first-load branch from 7f977e2 to 233f8b5 Compare November 19, 2026 21:10

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