> For the complete documentation index, see [llms.txt](https://docs.shoplift.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.shoplift.ai/api-reference/guides/javascript-api-tests/code-examples/offers-at-checkout.md).

# Give Each Test Group Its Own Offer at Checkout

Save a visitor's Shoplift test group to their Shopify cart, so a discount, shipping rate or free gift can give each group its own offer.

Shopify applies an automatic discount, a shipping rate or a free gift to every shopper who meets its conditions. It doesn't know which Shoplift test group a visitor is in. This guide shows how to save the visitor's group to their cart, so your checkout logic can give each group its own offer. It's for the developer who sets up the theme code and the discount.

**You need:** a Shoplift test · access to your theme code · a discount, shipping or gift setup that can read a cart attribute · about an hour

**Not a developer?** To choose how to test an offer, read [How can I test an offer or discount?](https://docs.shoplift.ai/learn/guides/test-offers-and-discounts)

### Before you start

* Create the test that shows each group its offer. It can be an API, template, theme, URL redirect or price test.
* Get the variant's hypothesis ID. See step 1 of [Add your own code to any test](https://docs.shoplift.ai/api-reference/guides/javascript-api-tests/code-examples/add-your-own-code-to-any-test.md).
* Choose how checkout will read the group: a [Shopify Function](https://shopify.dev/docs/apps/build/functions) that you build, or a discount or shipping app that supports cart-attribute conditions.

### Steps

#### 1. Save the visitor's group to the cart

Add this script to `layout/theme.liquid` in your live theme, just before the closing `</body>` tag, so it runs on every storefront page that uses your main layout (all of them, on most themes). For a theme test, add it to the variant theme as well, so it runs for both groups. It saves `variant` or `original` to a cart attribute named `offer_test_group`.

```javascript
function whenShopliftReady(timeoutMs = 5000) {
  return new Promise((resolve) => {
    const started = Date.now();
    (function check() {
      if (window.shoplift) return resolve(window.shoplift);
      if (Date.now() - started >= timeoutMs) return resolve(null);
      setTimeout(check, 100);
    })();
  });
}

async function saveOfferGroup() {
  const shoplift = await whenShopliftReady(15000);
  let group = "original";
  try {
    const inVariant = shoplift
      ? shoplift
          .getVisitorData()
          .visitorTests.some((test) => test.hypothesisId === "YOUR_VARIANT_HYPOTHESIS_ID")
      : false;
    if (inVariant) group = "variant";
  } catch (error) {
    group = "original";
  }
  try {
    const root = (window.Shopify && window.Shopify.routes && window.Shopify.routes.root) || "/";
    const cart = await fetch(root + "cart.js").then((response) => response.json());
    if (cart.attributes.offer_test_group === group) return;
    await fetch(root + "cart/update.js", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ attributes: { offer_test_group: group } }),
    });
  } catch (error) {
    // If the cart can't be updated, it keeps the group it saved last.
  }
}

saveOfferGroup();
```

* `YOUR_VARIANT_HYPOTHESIS_ID`: the variant's hypothesis ID.

Expected result: the cart's `offer_test_group` attribute is `variant` for visitors in the variant, and `original` for everyone else. That includes visitors outside the test and visitors whose page can't load Shoplift, so they keep your current offer.

Also call `saveOfferGroup()` after an item is added to the cart, for example when your theme's add-to-cart request finishes. That catches visitors who join a test partway through a page: a price test when a tested price scrolls into view, or a manual API test after your code triggers it. If Shoplift loads after the 15-second wait, the cart is saved as `original` on that page and corrected on the next one.

#### 2. Make checkout read the group

Set up your discount, shipping rate or gift so it applies the variant's offer only when `offer_test_group` is `variant`. Everyone else gets your current offer.

* **Shopify Function:** read the cart attribute `offer_test_group` in your function's input, and return the variant's offer only when it's `variant`. See Shopify's [discounts](https://shopify.dev/docs/apps/build/discounts) documentation.
* **An app:** add a condition on the cart attribute `offer_test_group`, if the app supports one.

Expected result: a cart with `offer_test_group` set to `variant` gets the variant's offer at checkout. Any other cart gets your current offer.

{% hint style="info" %}
**Treat the cart attribute as a convenience, not a lock.** Only test offers you'd be comfortable honoring for any shopper who gets them. This guide is public, so use your own attribute name and value in place of `offer_test_group` and `variant`.
{% endhint %}

#### 3. Check both groups through checkout

Open your store in a private browser window, reach the point where visitors join the test, and add a product to the cart. Then run this in your browser's console:

```javascript
fetch(window.Shopify.routes.root + "cart.js").then((response) => response.json()).then((cart) => cart.attributes);
```

Expected result: `offer_test_group` shows your group. Go on to the checkout page and confirm that the matching offer appears. Then close all private windows and open a new one. In most browsers, private windows share one session until you close them all. Repeat until you've checked both groups.

Visits you make this way are counted in the test's results, like any visitor's.

#### 4. When the test ends

Turn off the variant's offer, or make it everyone's offer if it won. Then remove the script. Carts saved during the test keep their `offer_test_group` value, so an offer that still requires `variant` keeps applying to those carts.

### Verify it worked

In each group, the offer on the checkout page matches the offer that group saw on your storefront. A visitor outside the test gets your current offer.

### Troubleshooting

**Both groups get the variant's offer**: the offer still applies without the cart-attribute condition. Check that the discount, shipping rate or gift reads `offer_test_group` and requires `variant`.

**Every visitor in a theme test gets the original offer**: the script is only in your live theme. Add it to the variant theme as well.

**A visitor in the variant gets the original offer**: the cart was saved before the visitor joined the test. Call `saveOfferGroup()` after add to cart, as in step 1.

**The variant's offer still applies while the test is paused**: the script can still find the visitor's group while the test is paused. Turn off the variant's offer in your discount while the test is paused.

**The attribute doesn't appear in the cart**: the script isn't running on that page, or Shoplift didn't load. Check that the script is in your theme's layout, and see [Common issues](https://docs.shoplift.ai/api-reference/debugging-and-testing/common-issues.md).

### Next steps

* [Add your own code to any test](https://docs.shoplift.ai/api-reference/guides/javascript-api-tests/code-examples/add-your-own-code-to-any-test.md)
* [getVisitorData()](https://docs.shoplift.ai/api-reference/javascript-api/javascript-api/getvisitordata.md)

**Related articles**

* [Testing shipping thresholds](https://docs.shoplift.ai/learn/guides/testing-shipping-thresholds)
* [How can I test an offer or discount?](https://docs.shoplift.ai/learn/guides/test-offers-and-discounts)

***

**Still need help?** [Contact support](https://docs.shoplift.ai/support/get-help) to chat with the Shoplift team in the app, or email <help@shoplift.ai>. Include your store URL and the name of your test.
