A Shopify free gift with purchase takes two parts. An automatic Buy X get Y discount makes the gift free once the cart qualifies, but Shopify does not put the gift in the cart. Your theme has to add the gift variant through the Cart Ajax API and take it out again when the cart stops qualifying. No Shopify Function adds a line to a cart.
Everything below was checked against Shopify’s documentation in November 2026. The Function code is written for API version 2026-10.
What does Buy X get Y do on its own?
It handles the price and nothing else. In the Shopify admin, create a Buy X get Y discount and set its method to automatic. Choose a minimum purchase amount for what the customer buys, pick the gift as what the customer gets, set its value to free, and cap the uses per order at one. Shopify’s help page for Buy X get Y is plain about the gap: the customer has to add every item to the cart, including the one they get free.
Two details from that page shape the script further down. The minimum purchase amount counts product prices only, so the script compares line prices and ignores shipping and tax. The gift also needs stock: once its inventory reaches zero the discount cannot be used, and the request to add it fails.
Once the gift sits in a qualifying cart, the saving shows before checkout. Automatic discounts apply in the cart and at checkout, and /cart.js reports the result on each line as final_line_price.
How do you add the gift to the cart automatically?
With a script that reads the cart, then adds or removes the gift line. The Cart Ajax API gives you GET /cart.js, POST /cart/add.js and POST /cart/change.js. Shopify asks for locale-aware URLs on every call, and window.Shopify.routes.root is the base it provides for building them.
const GIFT_VARIANT_ID = 44556677889900;
const THRESHOLD = 5000; // 50.00 in the subunit of the cart's currency
const TRIED_KEY = 'gift-tried-at';
const root = window.Shopify.routes.root;
const isGift = (item) => item.properties?._gift === 'true';
async function request(path, body) {
const response = await fetch(root + path, {
method: body ? 'POST' : 'GET',
headers: {'Content-Type': 'application/json'},
body: body && JSON.stringify(body),
});
if (!response.ok) throw new Error(`${path} returned ${response.status}`);
return response.json();
}
const removeLine = (item) =>
request('cart/change.js', {id: item.key, quantity: 0});
async function run() {
const cart = await request('cart.js');
const gifts = cart.items.filter(isGift);
const spend = cart.items
.filter((item) => !isGift(item))
.reduce((sum, item) => sum + item.final_line_price, 0);
const unwanted = gifts.find(
(item) => spend < THRESHOLD || item.final_line_price > 0,
);
if (unwanted) {
await removeLine(unwanted);
return run();
}
if (gifts.length || spend < THRESHOLD) return cart;
if (sessionStorage.getItem(TRIED_KEY) === String(spend)) return cart;
sessionStorage.setItem(TRIED_KEY, String(spend));
await request('cart/add.js', {
items: [{id: GIFT_VARIANT_ID, quantity: 1, properties: {_gift: 'true'}}],
});
const updated = await request('cart.js');
const added = updated.items.find(isGift);
if (!added) return updated;
if (added.final_line_price > 0) return removeLine(added);
sessionStorage.removeItem(TRIED_KEY);
return updated;
}
let queue = Promise.resolve();
export function syncGift() {
queue = queue.then(run, run);
return queue;
}
The gift line carries a line item property, _gift, so the script can tell the line it added from the same product bought on purpose. The leading underscore makes it a private property: Shopify hides it at checkout, the merchant still sees it on the order, and your cart template has to skip it itself.
Spend is the sum of final_line_price on every other line. /cart.js returns money in the shopper’s presentment currency, as integers in the subunit like the Liquid cart object, so a hard-coded 5000 means 50.00 of whatever they are browsing in. Set a threshold per currency if you sell in several.
The script does not trust its own arithmetic. After adding the gift it reads the cart back and checks that Shopify priced the line at zero. If the discount is paused, expired or set to a different threshold, the line comes back at full price and the script removes it, so the shopper is not charged for something the page called free.
It also writes the spend to sessionStorage before each attempt and skips the add while that figure is unchanged. Without that, a cart with no working discount would gain and lose a gift on every update, and a sold-out gift would be requested again and again. The reference warns that repeated failed adds to the same cart are throttled with a 429.
Calls are queued. Two quick clicks on a quantity button would otherwise both read a cart with no gift and both add one.
Call syncGift() on page load and after every cart change your theme makes. Then redraw the cart from the JSON it resolves with, or fetch fresh HTML through the Section Rendering API. As written, a shopper who removes the gift by hand gets it back on the next sync. If removal should stick, store a flag from your remove button and check it before the add.
Can a Shopify Function add the gift instead?
No. Two Function APIs change cart lines and neither creates one.
The Discount Function API returns operations that discount existing cart lines or the order subtotal. The Cart Transform Function API can expand a line the shopper added into components, which is how Shopify’s own example attaches gift wrap. That suits a gift tied to one product and sold as a bundle. It does not give you a gift on its own line at a spend threshold, a store gets one cart transform function per app, and Shopify rejects the operation when a selling plan is present.
A checkout UI extension can add a line with applyCartLinesChange and type: 'addCartLine', but it does not reach every buyer. Checkout UI extensions on the information, shipping and payment steps are limited to Shopify Plus, and the Cart Lines API returns an error when the buyer uses an accelerated checkout method such as Apple Pay or Google Pay.
A Function can replace the discount half when Buy X get Y cannot express the rule. That might be a lower threshold for tagged customers, tiers that swap one gift for another, or a gift that only the scripted line should receive. The code below handles the last of those. Line item properties reach a Function as cart line attributes, so the input query asks for _gift by key.
query CartInput {
presentmentCurrencyRate
cart {
lines {
id
gift: attribute(key: "_gift") {
value
}
merchandise {
__typename
... on ProductVariant {
id
}
}
cost {
subtotalAmount {
amount
}
}
}
}
discount {
discountClasses
}
}
const GIFT_VARIANT = 'gid://shopify/ProductVariant/44556677889900';
const THRESHOLD = 50; // in the shop's currency
const isGift = (line) =>
line.gift?.value === 'true' &&
line.merchandise.__typename === 'ProductVariant' &&
line.merchandise.id === GIFT_VARIANT;
export function cartLinesDiscountsGenerateRun(input) {
const none = {operations: []};
if (!input.discount.discountClasses.includes('PRODUCT')) return none;
const gift = input.cart.lines.find(isGift);
const spend = input.cart.lines
.filter((line) => !isGift(line))
.reduce((sum, line) => sum + Number(line.cost.subtotalAmount.amount), 0);
const threshold = THRESHOLD * Number(input.presentmentCurrencyRate);
if (!gift || spend < threshold) return none;
return {
operations: [
{
productDiscountsAdd: {
selectionStrategy: 'FIRST',
candidates: [
{
message: 'Free gift',
targets: [{cartLine: {id: gift.id, quantity: 1}}],
value: {percentage: {value: '100.0'}},
},
],
},
},
],
};
}
A line item property is sent by the browser, so anyone can post _gift on a GBP 900 jacket. That is why the Function also checks the variant ID, and discounts one unit only. presentmentCurrencyRate converts the threshold from the shop’s currency into the currency the line costs arrive in. The percentage is a string because the reference documents Decimal output values as strings.
In a real app the threshold and the variant come from the discount’s metafield, edited through a settings extension on the discount page, not from constants.
Where does the gift get skipped?
Anywhere the cart script does not run. The discount is still active in each of these cases, but there is no gift line for it to act on.
Buy it now and the other dynamic checkout buttons skip the cart and go to checkout with a single variant. A cart permalink does the same with whatever the link lists. Orders taken outside the online store never load your theme. The Buy X get Y help page adds two limits of its own: the discount reaches POS checkout only with POS Pro, and one created in the admin does not apply on the post-purchase page.
A discount code can undo the gift as well. If a shopper enters a code that is not set to combine with the gift discount, the two cannot both apply, and Shopify’s page on combining discounts says the best discount for the cart is the one applied. When that is the code, the gift line stays in the order at full price. The script would remove it in the cart, but a code typed at checkout arrives after the script has stopped running.
How would we build a Shopify free gift with purchase?
Start with the automatic Buy X get Y discount and the cart script. It needs no app. Put the threshold and the gift variant in theme settings so the merchant can change both sides in one sitting, and set the discount’s combinations on purpose before launch. The read-back check means a mismatched threshold costs a missing gift in the cart instead of an overcharge.
Move the discount half to a Function only when the rule outgrows Buy X get Y. Keep the script either way, because the Function still cannot add the line.
We would not build this for a store where most orders come through Buy it now, cart permalinks or the till. A gift that depends on a theme script will miss those orders. An automatic amount-off discount needs nothing added to the cart, so there is no script for it to miss.
We build Shopify themes, apps and Functions, including promotions like this one where the storefront and the discount have to agree. If yours has rules the admin cannot express, our Shopify development team can scope it.