Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 55 ยท Real-World Projects

Project: Checkout Upsell Extension

Build a Shopify checkout upsell extension: merchant settings, a recommendation engine, adding a cart line safely, and a runnable cart and ranking stand-in.

The checkout is the most valuable page of a shop, and a small, relevant offer ("Add a cleaning cloth for $4?") placed there can lift the average order value without sending the buyer anywhere else. Shopify lets apps do this with checkout UI extensions: small pieces of UI that Shopify renders inside checkout at fixed positions called targets. In this project you build a one-click upsell: the merchant picks products and a maximum number of offers, the extension picks the best ones for the current cart, and a button adds the offer to the cart.

The real extension (TOML, TSX, GraphQL) is read-only here, because it needs a Shopify checkout to run. The decisions (which products to offer, in which order, and what happens when the buyer clicks) live in plain JavaScript, and that part is a runnable stand-in with a fake cart. The lesson says which is which. The code follows the Preact-and-web-components style of recent checkout extension versions (this lesson targets 2026-07); the extension APIs have changed shape in the past, so check the current checkout UI extension documentation before you copy names. Background: Checkout UI Extensions, App Extensions Overview and Polaris and App Home Design.

Scope and rules

An upsell can be annoying or can be a genuine service. Decide the rules first:

  1. The merchant chooses candidate variants and a maximum number of offers (1 to 3).
  2. Never offer something already in the cart.
  3. Never offer something that is out of stock.
  4. Prefer cheaper add-ons when the cart is small and use the merchant's priority order as a tie-breaker.
  5. Keep the offer cheap compared with the cart: an add-on above half of the cart subtotal feels pushy and is skipped.
  6. One click adds one unit; the extension never changes quantities silently.
flowchart TD
    T["Checkout renders<br/>the extension target"] --> S["Read settings<br/>and cart lines"]
    S --> Q["Storefront query:<br/>candidate variants"]
    Q --> R["Recommendation rules"]
    R --> UI["Show up to N offers"]
    UI -->|"buyer clicks Add"| A["applyCartLinesChange<br/>(addCartLine)"]
    A -->|"success"| U["Cart updates,<br/>offer disappears"]
    A -->|"error"| E["Show message,<br/>keep checkout usable"]

The extension reads, decides and then asks checkout to change the cart. It never edits the cart itself.

The extension configuration

An extension is declared in a TOML file. The settings block creates the fields the merchant fills in the checkout editor (the page in the admin where merchants customise checkout). Network and API access are capabilities that must be declared; asking only for what you need keeps your app within App Store requirements.

TOML
# extensions/checkout-upsell/shopify.extension.toml (read-only)
api_version = "2026-07"

[[extensions]]
name = "Checkout upsell"
handle = "checkout-upsell"
type = "ui_extension"

  [[extensions.targeting]]
  module = "./src/Checkout.jsx"
  target = "purchase.checkout.cart-line-list.render-after"

  [extensions.capabilities]
  api_access = true          # lets the extension query the Storefront API

  [extensions.settings]
    [[extensions.settings.fields]]
    key = "variant_ids"
    type = "multi_line_text_field"
    name = "Variant ids to offer (one per line)"

    [[extensions.settings.fields]]
    key = "max_offers"
    type = "number_integer"
    name = "Maximum offers"

The target purchase.checkout.cart-line-list.render-after places the UI below the list of products in checkout. Targets are fixed positions; you cannot put UI anywhere you like, which is a feature: checkout stays fast and consistent. Settings arrive as strings or numbers that may be missing, so the code must handle empty values.

Fetching candidates

The extension needs each candidate's title, price and availability. It asks the Storefront API through the extension's query helper. The extension runs in a sandbox, so this is the sanctioned way to read shop data.

JSX
// src/Checkout.jsx (read-only sketch)
import "@shopify/ui-extensions/preact";
import { render } from "preact";
import { useEffect, useState } from "preact/hooks";

export default async () => render(<Upsell />, document.body);

const CANDIDATES = `#graphql
  query Candidates($ids: [ID!]!) {
    nodes(ids: $ids) {
      ... on ProductVariant {
        id
        title
        availableForSale
        price { amount currencyCode }
        product { title }
      }
    }
  }`;

function Upsell() {
  const [offers, setOffers] = useState([]);
  const [message, setMessage] = useState("");
  const lines = shopify.lines.value;                  // current cart lines (reactive)
  const settings = shopify.settings.value;            // merchant settings from the editor

  useEffect(() => {
    const ids = parseVariantIds(settings.variant_ids);
    if (ids.length === 0) return;
    shopify.query(CANDIDATES, { variables: { ids } }).then(({ data }) => {
      setOffers(pickOffers(data.nodes, lines, settings.max_offers, shopify.cost.subtotalAmount.value));
    });
  }, [lines.length, settings.variant_ids]);

  async function add(variantId) {
    const result = await shopify.applyCartLinesChange({
      type: "addCartLine", merchandiseId: variantId, quantity: 1,
    });
    if (result.type === "error") setMessage(result.message);
  }

  if (offers.length === 0) return null;
  return (
    <s-stack gap="base">
      <s-heading>You might also like</s-heading>
      {offers.map((o) => (
        <s-stack direction="inline" gap="base" key={o.id}>
          <s-text>{o.title} ({o.price})</s-text>
          <s-button onClick={() => add(o.id)}>Add</s-button>
        </s-stack>
      ))}
      {message && <s-banner tone="critical">{message}</s-banner>}
    </s-stack>
  );
}

Things worth noticing in this sketch: the shopify global provides reactive values, the settings and the cart-change function; the component returns null when there is nothing to show, so checkout is untouched; and the click handler checks the result type, because applyCartLinesChange reports failure (for example when stock ran out) instead of throwing. pickOffers is the part you can test without Shopify, so you write it as a pure function in its own file.

The recommendation logic

Node.js Choosing offers: filters, ranking, limits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Walk through the first result. The gift wrap is skipped (it is already in the cart), the sold-out charm is skipped, the warranty and the travel case are too expensive for a $30 cart (above half the subtotal), so only the cloth remains. For the $200 cart all three offers fit under the price rule and are listed cheapest first. Money is held as integer cents and formatted only at the very end, for the reasons in Money as Integers. Merchandising theory such as "frequently bought together" is in Merchandising and Recommendations.

Adding to the cart safely

The click handler is the risky part: it changes what the buyer pays. Rules to follow:

  • One click, one unit. Disable the button while the request runs, otherwise a double click adds two.
  • Read the result. On error, show a short message and keep the offer visible.
  • Never retry silently. The buyer decides what is in their cart.
  • Do not add things that need extra input, such as products with required properties; send those buyers to the product page instead.
Node.js A cart stand-in with applyCartLinesChange

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The double click adds only one unit, the second request for v2 fails with a readable message, and the unknown variant is refused. That is exactly the behaviour you want from the real handler; the stand-in simply replaces checkout with an array.

Testing and shipping

Test the pure functions with unit tests, as in Project: Tiered Volume Discount. Then test in a development store with shopify app dev, and try these situations by hand: an empty settings list, a candidate that is sold out, a cart that already contains the offer, a very small cart, a buyer using a discount code, and a slow connection. Also check the extension's bundle size and its time to first render: checkout extensions are part of the page's performance, which is part of the review described in App Store Requirements and Review.

Finally, deploy with shopify app deploy. The merchant then opens the checkout editor in the admin, adds your block at the target, and fills in the settings.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does the merchant enter the variant ids and the maximum number of offers?

    Extension settings are declared in the extension's TOML and rendered by Shopify in the checkout editor. The extension reads them at runtime.
  2. 2. What should the extension do when applyCartLinesChange returns an error result?

    The call reports failure as a result, for example when stock runs out. Show the message, keep the offer, and leave the buyer in control of the cart.
  3. 3. Why does the example filter out offers priced above half of the cart subtotal?

    This is a merchandising rule chosen for the project, not a platform limit. Rules like this are easy to test because they live in a pure function.
  4. 4. Why return null from the component when there are no offers?

    An upsell that has nothing to offer should be invisible. A heading with an empty list would look broken.

Summary

  • A checkout UI extension renders at a fixed target, reads settings and cart lines from the shopify global, and asks checkout to change the cart.
  • Keep the offer logic in a pure function: filter what is in the cart or out of stock, apply a price rule, rank, and cut at a limit.
  • Handle missing or odd settings values; hold money in integer cents.
  • Guard the add button against double clicks and always read the result of applyCartLinesChange.
  • Test the logic with unit tests and the UI in a development store, then deploy with shopify app deploy.

Next, charge for your work in Project: A Paid App with Plans and Usage Billing.