Skip to content

fix(merch): report checkout failures and stop the cart hydration mismatch - #20294

Closed
posthog[bot] wants to merge 1 commit into
masterfrom
posthog-self-driving/fixmerch-stop-checkout-failing-silently-f51804
Closed

posthog[bot] wants to merge 1 commit into
masterfrom
posthog-self-driving/fixmerch-stop-checkout-failing-silently-f51804

Conversation

@posthog

@posthog posthog Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Changes

Two defects on /merch make the Checkout control fail without saying so. This fixes both.

Problem

  • Shoppers lose the cart they built: the Checkout control is the store's only conversion action, and when it fails they get no message, no retry hint, and no path forward except to abandon the purchase. Session replay in the linked report shows people give up.
  • createCartQuery caught every error and resolved undefined. The caller then read cart.id, so the failure surfaced as an unhandled TypeError and the button kept spinning.
  • The cart store read local storage while React hydrated the page. The server renders an empty cart, so the two trees did not match. React discarded the server tree, rendered /merch again, and every piece of component state went back to its default value — including the cart panel flag, which was plain local state.

Changes

  • Storefront requests now reject instead of swallowing: one shared helper rejects on a failed request, on GraphQL errors, and on cartCreate.userErrors (which the mutation did not even ask for before).
  • The checkout handler catches the rejection, clears the loading state, shows a failure message, and captures merch_checkout_failed with the error text and the cart size. Silent failures become countable ones.
  • The store reads local storage in an effect behind a hasHydrated flag, so the first client render matches the server HTML.
  • The cart panel flag moved from useState into the store, so a re-render of the page cannot close the panel.
Failure Before After
Shopify returns HTTP 5xx, or the network drops button spins forever, unhandled TypeError message on screen, spinner cleared, event captured
Shopify reports userErrors (for example an invalid merchandise line) not requested, not read request rejects with the Shopify message
Shopify returns no checkoutUrl click does nothing at all request rejects, message on screen
Cart in local storage on page load React error #418 then #423, page renders again no hydration error
🗺️ PR tour

Stop 1: The Storefront request layer (diff)

createCartQuery and getCartQuery duplicated the same fetch chain, and each ended in a catch that hid the error — one returned undefined, the other rewrapped the error and lost its message. Both now call one helper that rejects.

/**
* Post a document to the Storefront API. Rejects if the request fails or if the
* API reports an error, so the caller can tell the shopper what went wrong.
*/
async function postToStorefront<TData>(query: string, variables?: Record<string, unknown>): Promise<TData> {
const response = await fetch(shopifyStorefrontUrl, {
method: 'POST',
headers: shopifyHeaders,
body: JSON.stringify({ query, variables }),
})
if (!response.ok) {
throw new Error(`Shopify request failed with status ${response.status}`)
}
const { data, errors } = (await response.json()) as StorefrontResponse<TData>
if (errors?.length) {
throw new Error(errors[0].message)
}
if (!data) {
throw new Error('Shopify returned no data')
}
return data
}
export const createCartQuery = async (variables: CreateCartVariables): Promise<Cart> => {
const { cartCreate } = await postToStorefront<CartCreateReponse>(CREATE_CART, variables)
if (cartCreate.userErrors?.length) {
throw new Error(cartCreate.userErrors[0].message)
}
if (!cartCreate.cart) {
throw new Error('Shopify returned no cart')
}
return cartCreate.cart
}
export const getCartQuery = async (id: string): Promise<Cart | null> => {
const { cart } = await postToStorefront<CartResponse>(GET_CART, { id })
return cart
}

The CartCreateMutation document now also asks for userErrors, and CartCreateReponse in src/templates/merch/types.ts describes the shape Shopify actually returns (cartCreate.cart, not cartCreate as the cart).

⚠️ createCartQuery used to resolve Promise<CartCreateReponse | void> and now resolves Promise<Cart> or rejects. Checkout.tsx is the only caller.

Stop 2: The checkout handler (diff)

The mutation keeps its shape. The call site now handles the rejection, so the shopper sees a failure instead of a frozen button.

setIsCheckingOut(false)
return
}
const checkoutUrl = getCheckoutUrl(cart, discountCode)
if (!checkoutUrl) {
throw new Error('Shopify returned no checkout URL')
}
// the browser leaves the page here, so the button keeps its loading state
window.location.href = checkoutUrl
}
checkoutMutation().catch((error: unknown) => {
posthog?.capture('merch_checkout_failed', {
error: error instanceof Error ? error.message : String(error),
cart_item_count: cartItems.length,
})
setHasFailed(true)
setIsCheckingOut(false)
})
}, [cartId, cartItems, discountCode, allProducts, posthog, setCartId, setCartItems])

Two details worth naming:

  • A missing checkoutUrl used to make the click do nothing. It now throws, so it reaches the same message.
  • The loading state is not cleared on the success path. The browser is leaving the page, and a cleared spinner there looks exactly like the bug being fixed.

The failure message sits above the button, which doubles as the retry.

<div className={classes}>
{adjustedItems.length > 0 && <AdjustedLineItems className="my-4" lineItems={adjustedItems} />}
{hasFailed && (
<p role="alert" className="mb-2 text-sm font-normal text-red dark:text-yellow">
We could not start your checkout. Please try again.
</p>
)}
<div className="flex justify-end">

Stop 3: The cart store (diff)

skipHydration stops the store from reading local storage during render. useCartStoreHydration does the read in an effect and reports when it is done. partialize names what survives a reload: the cart contents, not the panel flag and not the hydration flag.

{
name: 'merch-cart',
// Local storage is read on the first client effect, not during render. See useCartStoreHydration.
skipHydration: true,
// the cart contents outlive a reload, but the panel and the hydration flag do not
partialize: (state) => ({
cartId: state.cartId,
cartItems: state.cartItems,
count: state.count,
subtotal: state.subtotal,
discountCode: state.discountCode,
checkoutUrl: state.checkoutUrl,
}),
onRehydrateStorage: () => () => useCartStore.setState({ hasHydrated: true }),
}
)
)
/**
* Read the cart from local storage after React hydrates the page.
*
* The server cannot read local storage, so it renders an empty cart. If the client
* read the cart during its first render instead, the two trees would not match,
* React would discard the server tree and render the whole page again, and every
* piece of component state would go back to its default value.
*
* Call this hook in each component that shows persisted cart state.
*/
export function useCartStoreHydration(): boolean {
const hasHydrated = useCartStore((state) => state.hasHydrated)
useEffect(() => {
if (!useCartStore.persist.hasHydrated()) {
useCartStore.persist.rehydrate()
}
}, [])
return hasHydrated
}

⚠️ This stop also deletes a module-level subscription that fetched the cart on a full reload. It was dead: the subscription immediately unsubscribed itself, and its fireImmediately pass ran before any cart id existed. The stale-cart case it guarded is already covered, because the cartItems subscription below clears cartId on every change.

Stop 4: The cart panel flag (diff)

Collection reads the panel flag from the store instead of useState, and its URL initialization waits for the cart to load. The else branch now sets the flag from the URL in both directions, which keeps the URL authoritative.

const { getJwt, user } = useUser()
const isMobile = appIsMobile || (appWindow?.size?.width && appWindow.size.width <= 768)
const addToCart = useCartStore((state) => state.update)
// the cart panel flag lives in the store, so a re-render of this page cannot close the panel
const cartIsOpen = useCartStore((state) => state.isOpen)
const setCartIsOpen = useCartStore((state) => state.setIsOpen)
const hasHydrated = useCartStoreHydration()
const hasProcessedAddToCart = useRef(false)

Stop 5: The other two cart consumers (diff)

HeaderBar renders the cart count in text, so it was a hydration mismatch of its own; it now triggers the local storage read. useDesktopBadges had a bespoke mounted flag for the same reason, and uses the shared flag instead.

export default function useDesktopBadges(): DesktopBadges {
const cartCount = useCartStore((state) => state.count)
const hasHydrated = useCartStoreHydration()
return useMemo(() => {
if (!hasHydrated) return EMPTY
// The Store badge stays mounted at `count={0}`, where it renders nothing.
// Dropping the entry instead would unmount the element outright and skip
// NotificationBadge's exit animation when the cart empties.
const badges: DesktopBadges = {
'/merch': <NotificationBadge count={cartCount ?? 0} />,
}
return badges
}, [hasHydrated, cartCount])
}

🔍 Reviewer's guide

Testing done

Check Command / method Result
Types tsc --noEmit -p tsconfig.json 0 errors under src/ (unchanged from master)
Formatting prettier --write on the 7 changed files Applied, no further changes
Request layer Compiled src/lib/shopify.ts, drove it with a stub fetch over 8 cases: HTTP 500, GraphQL errors, userErrors, no cart, network throw, success, unknown cart, HTTP 502 All 8 behave as expected; every failure rejects, success resolves the cart
Checkout, failure path Rendered the real Checkout component in jsdom with a failing fetch, clicked the button Message on screen, spinner class cleared, one merch_checkout_failed capture with the error text and cart_item_count
Checkout, retry path Same harness, then answered the next request with a cart Message cleared, redirect set to the Shopify checkout URL, spinner kept on, no second event
Same harness against master Compiled the pre-change files, same failing fetch Reproduces the report: no message, spinner still turning, unhandled TypeError: Cannot read properties of undefined (reading 'id')
Hydration jsdom harness that mirrors the store: renderToString with no local storage, then hydrateRoot with a cart in local storage, counting onRecoverableError master shape: 2 recoverable errors (text content mismatch, then the server HTML replaced — #418 and #423). This branch: 0. The cart count and the cart panel still restore.

Not tested: the dev server and the Vercel preview. pnpm start cannot build /merch in this environment — the page comes from allShopifyProduct nodes, and the Shopify credentials are absent from .env.development.

Screenshots

Blocker — not supplied. This environment has no browser binary and cannot build /merch, so the required grid (light and dark, narrow and wide) could not be captured. The PR stays a draft until a maintainer supplies it. One new visual state needs the grid:

State Before After
Light, narrow window not captured not captured
Light, wide window not captured not captured
Dark, narrow window not captured not captured
Dark, wide window not captured not captured

To reach the state: open the cart with an item in it, block the request to the Shopify Storefront API in devtools, then click Checkout. The message renders above the button.

What to look at

  1. src/templates/merch/store.ts:70 — skipHydration is the highest-blast-radius line here. Every consumer of the cart now shows an empty cart until the first effect runs, and HeaderBar is global, not merch-only. A consumer that reads persisted cart state and does not call useCartStoreHydration would show an empty cart forever. Three consumers exist today and all three call it.
  2. src/templates/merch/Collection.tsx:194 — the URL initialization now waits for hasHydrated. It is the same component's own hook that sets the flag, so the wait is short, but if that ever stops being true then ?product=, ?state=cart and ?add= deep links stop working. Worth a second pair of eyes on the ordering.
  3. partialize dropping isOpen — my judgment call. Keeping the panel flag out of local storage means the URL alone decides whether the panel is open, and it removes a frame where a stored isOpen: true would open the panel and the URL would then close it. It also means the stored payload loses a key that older code wrote. Push back if you would rather persist it.

Checklist

  • I've read the docs and/or content style guides.
  • Words are spelled using American English
  • Use relative URLs for internal links — no links added
  • I've checked the pages added or changed in the Vercel preview build — a reviewer must do this; see "Not tested" above
  • If I moved a page, I added a redirect in vercel.json — no page moved

Created with PostHog Desktop from this inbox report.

…atch

The merch checkout button could fail with no message. createCartQuery caught
every error and resolved undefined, the caller then read cart.id, and the
TypeError became an unhandled rejection that left the button spinning.

The cart store also read local storage during the first client render, which
does not match the server HTML. React then discarded the server tree and
rendered the page again, which reset every piece of component state, including
the cart panel flag.

- createCartQuery and getCartQuery now share one request helper that rejects on
  a failed request, on GraphQL errors, and on cart user errors
- the checkout handler catches the rejection, clears the loading state, shows a
  failure message, and captures merch_checkout_failed
- the cart store reads local storage in an effect, behind a hasHydrated flag
- the cart panel flag moved into the store, so a re-render cannot close it

Generated-By: PostHog Desktop
Task-Id: e8b68ab3-4315-4b03-9bc8-adc34ba968e5
@github-actions github-actions Bot added the website About the website (beyond just landing pages) label Sep 18, 2026
@github-actions

github-actions Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Deploy preview

Status Details Updated (UTC)
🟢 Ready View preview Sep 18, 2026 01:08PM

@github-actions

Copy link
Copy Markdown
Contributor

Bundle report

Total JS (gzip)

8.66 MiB (+1.2 KiB / +0.0%)

Eager graph (modules shipped in each entrypoint's initial chunks)

Entrypoint Eager size Budget Modules
✅ app 18.58 MiB (-5.1 KiB / -0.0%) report-only 2066
Largest modules in the app closure
Module Size
./src/data/mcp-tools.json 1163.3 KiB
css ./node_modules/.pnpm/css-loader@5.2.7_webpack@5.101.3/node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[8].oneOf[1].use[1]!./node_modules/.pnpm/postcss-loader@4.3.0_postcss@8.5.6_webpack@5.101.3/node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[8].oneOf[1].use[2]!./src/styles/global.css 773.1 KiB
./src/components/Stickers/Stickers.tsx 696.4 KiB
./node_modules/.pnpm/@radix-ui+react-icons@1.3.2_react@18.3.1/node_modules/@radix-ui/react-icons/dist/react-icons.esm.js 481.4 KiB
./node_modules/.pnpm/@posthog+brand@0.8.0_react@18.3.1/node_modules/@posthog/brand/dist/generated/hoggies/svg/x-ray.mjs 480.8 KiB
./node_modules/.pnpm/rehype-raw@7.0.0/node_modules/rehype-raw/lib/index.js + 29 modules 395.1 KiB
./node_modules/.pnpm/@posthog+brand@0.8.0_react@18.3.1/node_modules/@posthog/brand/dist/generated/hoggies/svg/im-the-driver.mjs 385.7 KiB
./src/hooks/useCustomers.tsx + 55 modules 372.5 KiB
./node_modules/.pnpm/@posthog+icons@0.36.6_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@posthog/icons/dist/posthog-icons.es.js 354.8 KiB
./node_modules/.pnpm/react-markdown@8.0.7_@types+react@16.14.66_react@18.3.1/node_modules/react-markdown/lib/react-markdown.js + 88 modules 351.4 KiB
./src/components/ProductComparisonTable/index.tsx + 126 modules 305.8 KiB
./node_modules/.pnpm/cloudinary-core@2.14.0_lodash@4.17.21/node_modules/cloudinary-core/cloudinary-core.js 281.9 KiB
./node_modules/.pnpm/@posthog+brand@0.8.0_react@18.3.1/node_modules/@posthog/brand/dist/generated/hoggies/svg/doll-house.mjs 281.7 KiB
./node_modules/.pnpm/@posthog+brand@0.8.0_react@18.3.1/node_modules/@posthog/brand/dist/generated/hoggies/svg/director.mjs 275.6 KiB
./src/components/SearchUI/index.tsx + 87 modules 273.7 KiB

Eager-graph budgets are report-only until a baseline is established. Sizes are gzip of public/**/*.js; eager size is webpack module source bytes for the modules actually shipped in the entrypoint's initial chunks (post-tree-shake).

@github-actions

github-actions Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

This PR hasn't seen activity in two weeks! Should it be merged, closed, or further worked on? If you want to keep it open, please remove the stale label – otherwise this will be closed in another week. If you want to permanently keep it open, use the waiting label.

@github-actions github-actions Bot added the stale This pull request has been marked as stale and will be closed soon automatically label Oct 5, 2026
@github-actions

Copy link
Copy Markdown
Contributor

This PR was closed due to lack of activity. Feel free to reopen if it's still relevant.

@github-actions github-actions Bot closed this Oct 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stale This pull request has been marked as stale and will be closed soon automatically website About the website (beyond just landing pages)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants