DEV Community

Cover image for Shopify Pre-Order Button Bug: Fix Stale Responses
Aqib Javaid
Aqib Javaid

Posted on Originally published at aqibjavaid.site

Shopify Pre-Order Button Bug: Fix Stale Responses

A fan opens a hoodie on a merch store during a drop, flicks to the next product, then the next. The "Pre-order" button on the hoodie they are looking at actually belongs to the shirt they opened two taps ago. They tap it anyway. That is a Shopify pre-order button bug, and it is the kind that creates refunds and angry support emails, because the cart now holds the wrong kind of line item.

I hit this design problem on the Osamason merch store, where a single quick-view component checks a pre-order app before it decides what the buy button says. The fix is small, but the reasons behind it are worth knowing if you are doing ecommerce development and integrations where a storefront asks a third-party service a question before it lets a customer buy. This article shows the bug, a reproduction with numbers, three ways to fix it, and where each one stops being enough.

The setup: a button that depends on a slow answer

The store runs a custom Shopify theme. Clicking a product card opens a full-screen quick view, and previous and next arrows move through the grid. Many merch products sell before stock exists, so the buy button must read "Pre-order" for those and "Add to cart" for the rest, and the cart request must carry the right pre-order line item properties.

The pre-order state comes from an app, not from the theme. When a product opens, the theme asks the app, through a Shopify app proxy, whether this product and the selected variant qualify. That is one network round trip per product, and its duration is not under the theme's control.

So the button's state is a function of an asynchronous answer. That is the whole problem. Any time UI state depends on a response that can arrive late, you have to decide what happens when the user has moved on before it lands.

The bug in 12 lines

The naive version is what almost everyone writes first:

async openProduct(handle) {
  this.button.textContent = 'Loading...';
  const res = await fetch(`/apps/preorder/check?handle=${handle}`);
  const { preorder } = await res.json();
  this.button.textContent = preorder ? 'Pre-order' : 'Add to cart';
}
Enter fullscreen mode Exit fullscreen mode

It works on a fast connection with one product. It breaks when two calls overlap. Call A starts for the shirt, call B starts for the hoodie, B returns first and paints "Add to cart", then A returns and overwrites it with "Pre-order". The screen shows the hoodie, the button reflects the shirt, and nothing in the code looks wrong because every line did exactly what it said.

This is the same family of bug as the check-then-update gap I wrote about in the Laravel double-accept race condition, only in the browser: two operations interleave and the last writer wins, not the latest intent.

How often does it actually happen?

I do not want to hand-wave "it can happen", so I reproduced it. This is my own test harness, not client traffic. A mock endpoint answered with a random delay between 40 ms and 900 ms and a fixed rule (every third product is a pre-order). A headless Chromium script opened 6 random products, 120 ms apart (a fast thumb on an arrow button), waited for every response, and checked whether the button matched the last product opened. I ran 150 sequences per variant.

Variant Correct final state Wrong final state
Naive (last response wins) 117 of 150 (78%) 33 of 150 (22%)
Request token (ignore stale responses) 150 of 150 0
AbortController (cancel the previous request) 150 of 150 0

The wrong state shows up in roughly one in five fast flick-throughs, in a test where the longest delay is under a second. On a mobile connection during a drop, delays are longer and more variable, so I would expect it to be at least as common. The exact percentage depends on my delays and sequence length, so treat 22% as "this is not rare", not as a benchmark of any real store.

Fix 1: a request token

The approach used on the Osamason theme is a monotonically increasing token. Every call takes the next number, and a response is only allowed to touch the UI if its number is still the latest.

async openProduct(handle) {
  const token = ++this.requestToken;
  this.button.textContent = 'Loading...';
  this.button.disabled = true;

  try {
    const state = await this.getPreorderState(handle);
    if (token !== this.requestToken) return; // a newer product was opened
    this.render(state);
  } catch (e) {
    if (token !== this.requestToken) return;
    this.button.textContent = 'Please try again';
  }
}
Enter fullscreen mode Exit fullscreen mode

Two details matter more than the token itself.

  • Loading and failure states are deliberate. While the check runs, the button reads "Loading..." and is disabled. If the check fails, it reads "Please try again", not "Add to cart". The rule is that a pre-order item must never be addable as a regular purchase because a request failed. When in doubt, the safe default is "cannot buy yet", not "assume it is in stock".
  • The stale check also covers errors. A slow failure from an old request must not replace the correct button state of the current product, so the catch branch tests the token too.

The token costs one integer and does not need any browser API, which is why I like it for theme code that has to run on older phones.

Fix 2: cancel the old request

AbortController is the more "correct" tool because it stops the wasted work too:

openProduct(handle) {
  this.controller?.abort();
  this.controller = new AbortController();
  const { signal } = this.controller;

  return fetch(`/apps/preorder/check?handle=${handle}`, { signal })
    .then(r => r.json())
    .then(state => this.render(state))
    .catch(e => { if (e.name !== 'AbortError') this.showRetry(); });
}
Enter fullscreen mode Exit fullscreen mode

The AbortController documentation on MDN covers browser support, which is good for current browsers. In my test it scored the same as the token, 150 of 150. The practical difference is that an aborted request still may have run on the server, so you save bandwidth but not server work. On a store where the proxy hits an app's backend, that is a small win, not a big one.

I would use both in a codebase where the check is expensive: abort to stop the waste, and a token as the safety net, because a response can still sneak in between the abort and the next render if the code gets refactored.

Fix 3: cache the answer per product

On the Osamason theme, results are also cached per product, so reopening a product is instant. A cache does not replace the token, it removes most of the waiting that makes the race possible in the first place:

async getPreorderState(handle) {
  if (!this.cache.has(handle)) {
    this.cache.set(handle, this.fetchState(handle)); // store the promise
  }
  return this.cache.get(handle);
}
Enter fullscreen mode Exit fullscreen mode

Storing the promise, not the resolved value, means two quick opens of the same product share one request. Two things to watch:

  1. Do not cache failures. If fetchState rejects, delete the key, or a one-off network error will lock a product on "Please try again" until the page reloads.
  2. Think about freshness. Pre-order status changes when the merchant flips it in the app. Per-session caching is fine for a drop that lasts a few hours, but not for state that must be live. If stock or pre-order eligibility can change while someone is on the page, re-check right before the cart request.

When this is overkill, and when it is not

You do not need any of this when the state is rendered by Liquid on the server. If the product page already knows whether the item is a pre-order when it is built, the browser never has to ask. Shopify's server-side data is the most reliable source, and a client-side check should only exist where the answer genuinely lives in another system.

You do need it when:

  • the UI can switch between items without a page load (quick views, carousels, variant pickers);
  • the answer comes from a third-party app or API with variable latency;
  • a wrong answer has a cost: a pre-order sold as in-stock, a wrong price, a wrong shipping promise.

Also remember that the button is a hint, not a guard. The cart request that follows should send the line item properties for the product that was actually rendered, using the Ajax Cart API, and anything money-related still needs a server-side check. The same thinking applies to retries on the backend, which is where idempotency keys for API writes come in.

Why a custom theme was worth it here

Shopify's defaults would not have given this quick view at all. It is one custom element rendered once in the layout that intercepts product-card clicks across the store, so new sections get quick view for free. That design is also what makes the stale-response problem visible: once a single component serves every product, it has to cope with being asked a new question before it finished answering the last one.

If you are weighing a custom storefront against a standard theme and apps, my comparison of Shopify versus custom ecommerce lists where custom starts to pay off. For storefront work that involves third-party apps and carts, see my ecommerce development and integrations service page linked above, or get in touch via the contact page.

Frequently asked questions

Why does my Shopify button show the wrong state after quick switching?

Usually because an older asynchronous response arrives after a newer one and overwrites it. Tag each request with a token, or abort the previous request, and ignore anything that is not the latest.

Is AbortController or a request token better?

AbortController is cleaner and cancels network work. A token works everywhere and also protects against late responses after refactors. In a theme I would start with the token and add abort when requests are expensive.

Can I cache the pre-order check?

Yes, per product and per session, as long as you cache the promise, never cache failures, and re-check before adding to cart when the state can change during the visit.

Should a failed check fall back to "Add to cart"?

No. Fail closed. Show a retry state, so a product that should be a pre-order can never be bought as a normal item by accident.

Key takeaways

  • Any UI state that depends on a slow response needs a rule for what happens when the user moves on first.
  • In my reproduction, the naive version showed the wrong button in 33 of 150 fast flick-throughs; a token or an abort fixed all of them.
  • Fail closed: "Loading..." and "Please try again" are safer than guessing.
  • Cache promises, not failures, and re-check where the answer can change.

If you are building a storefront or an integration where a wrong button costs money, book a call and I will tell you where I would put the checks.


Originally published at aqibjavaid.site.

Top comments (0)