Promotion codes

Discounts for Cart-Backed Checkout

Throttle supports percentage, fixed amount and free-shipping promotion codes. The payment processor does not validate or calculate codes; Throttle computes the discounted cart total before checkout hands the final amount to payment.

1

Create a discount

Use the dashboard or API to create a percentage, fixed amount or free-shipping discount code.

2

Preview in your storefront

Call /api/v1/discounts/preview from your server when the buyer enters a code.

3

Apply to a cart

When checkout starts, apply the valid code to the Throttle cart before creating the checkout session.

4

Lock totals

Run shipping/tax calculation and checkout_final against the discounted cart before payment.

Supported types

Percentage off

type: "percentage", with value: 25 for 25% off.

Fixed amount off

type: "fixed_amount", with value: 500 for $5.00 off in minor units.

Free shipping

type: "free_shipping". It has no value; it takes the delivery price off. See Free-shipping codes.

A code applies after each line's own discountAmount (a manual discount the merchant set on the line or spread from an order discount). A 10% code on a $500 cart with $50 already off its lines takes $45, not $50, and a fixed-amount code is capped at what the lines come to after their discounts.

Removed discount type
Buy-X-get-Y is no longer an active product surface. Existing historical rows may remain inactive, but new code should only create percentage, fixed amount or free-shipping discounts.

Free-shipping codes

A free-shipping code makes delivery free for the orders it fits, by region and by shipping option, and can be limited to customer groups like any other code. It never changes a goods line's discount or the tax on goods.

A free-shipping code with a cap and a minimum
curl -X POST https://api.usethrottle.dev/api/v1/discounts \
  -H "X-API-Key: sk_live_xxx" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Free ground shipping over $50",
    "code": "SHIPFREE",
    "type": "free_shipping",
    "conditions": {
      "shipping": {
        "zoneIds": ["zone_us"],
        "targets": [
          { "kind": "method", "methodId": "flat_rate" },
          { "kind": "carrier_service", "provider": "shippo", "carrier": "UPS", "serviceCode": "ups_ground" }
        ]
      }
    },
    "amounts": { "USD": { "value": 1500, "minOrder": 5000 } }
  }'
  • conditions.shipping.zoneIds lists the shipping zones the code applies to, matched against the ship-to address. null means all regions.
  • conditions.shipping.targets lists the options the code makes free: { kind: "method", methodId } for a native method, or { kind: "carrier_service", provider, carrier, serviceCode } for a live carrier service. null means any option. An empty list is refused in both fields; send null. The API still accepts the legacy { kind: "method", methodId: "flat_rate" } target, but it cannot apply end to end: a cart on the flat-rate fallback has no selected shipping method, so the code reads pending_shipping and charges full shipping. The dashboard does not offer it; use a native method or carrier service target, or null.
  • The cap and the minimum are per currency. amounts[CUR].value is an optional cap on the reduction (no cap means free in full) and amounts[CUR].minOrder is the minimum goods subtotal. A code with caps is offered only in the currencies that have one. value itself is 0.
  • The type is immutable. An update that changes it answers discount_type_immutable.
  • Custom shipping is never touched. A typed amount (the dashboard's custom shipping) and a quote's flat or free shipping stay as set. A store that does not charge shipping refuses the code with 422 discount_not_applicable.
  • Subscription renewals are out. The code applies to the order it is used on.
  • Bring-your-own shipping records the code only if you send the reduction. When shipping is in bring-your-own mode, your checkout prices the shipping, so Throttle cannot see what the code took off. Send shippingDiscountAmount (minor units) on POST /api/v1/shipping-tax/external-snapshots for any cart that holds a free-shipping code, with selectedShipping.rateAmount as the original price (rateAmount = totals.shippingTotal + shippingDiscountAmount). Without it the order records no shipping code and the code's use is not counted against its limits. A value above the shipping price, or on a cart with no free-shipping code, answers 400 invalid_shipping_discount.

On the cart, the session and the order

Every cart, cart session and checkout session carries shippingDiscountTotal (0 without a code) and appliedShippingDiscount (null without one). shippingTotal is the shipping the buyer pays, already net of the code, so the price before the code is shippingTotal + shippingDiscountTotal. appliedDiscount is the goods code only; its freeShipping flag is gone. Orders and invoices carry shippingDiscountTotal and shippingDiscountCode.

appliedShippingDiscount
{
  "shippingTotal": 0,
  "shippingDiscountTotal": 1200,
  "appliedShippingDiscount": {
    "discountId": "0b8f...",
    "code": "SHIPFREE",
    "amount": 1200,
    "status": "applied",
    "zoneIds": ["zone_us"],
    "targets": [{ "kind": "method", "methodId": "flat_rate" }],
    "cap": 1500
  }
}
  • applied: the code reduces shipping now. amount is the reduction.
  • pending_address and pending_shipping: the code is on the cart but there is no ship-to address or no selected shipping option to judge yet.
  • not_eligible with a reason of zone, shipping_option or minimum_order (with amountToMinimum): the code stays on the cart with a reduction of 0 and works again once the cart qualifies. Use zoneIds, targets and cap to explain the rule ("US only", "Add $12 more").
  • merchant_applies: your store prices shipping itself, so Throttle cannot; your checkout honours the rule.

The shipping methods a shipping-tax calculation offers carry discountedAmount when the code would apply to them, so a custom checkout can show the price with the code beside the full price. The amount stays the full price.

Usage is counted only when the order's shippingDiscountTotal is above 0, so a code that sat on a cart that never qualified is not used up. Group, date and usage-limit failures remove the code from the cart, as they do for goods codes; a group-limited code a buyer is not eligible for answers exactly like an unknown code.

Use the SDK

@usethrottle/discounts is a server-side, headless SDK. It does not ship a coupon input UI; your checkout owns that field.

Install
npm install @usethrottle/discounts
Preview and apply
import { DiscountsClient } from '@usethrottle/discounts';

const discounts = new DiscountsClient({
  apiKey: process.env.THROTTLE_API_KEY!,
});

const preview = await discounts.preview({
  code: 'SUMMER25',
  currency: 'USD',
  subtotal: 10000,
  customerId,
});

if (preview.valid) {
  await discounts.applyToCart('cart_123', preview.code);
}

Preview without mutation

Use preview when the buyer types a code in your order summary. It returns the discount amount and total without creating or changing a cart. Include a customer ID when you want the preview to check the customer redemption limit.

POST /discounts/preview
const res = await fetch(`${process.env.THROTTLE_API_URL}/api/v1/discounts/preview`, {
  method: 'POST',
  headers: {
    'x-api-key': process.env.THROTTLE_API_KEY!,
    'content-type': 'application/json',
  },
  body: JSON.stringify({
    code: 'SUMMER25',
    currency: 'USD',
    subtotal: 10000,
    customerId: '00000000-0000-0000-0000-000000000000',
  }),
});

const { data } = await res.json();
// data.valid, data.discountTotal, data.total, data.message

When a code has a minimum order total and the order is under it, the validate and preview responses add minimum (the code's minimum in the order's currency) and shortfall (how much more the order needs to reach it). Both are money values: { amount, currency, display }, where amount is in minor units and display is the formatted string, for example €12.50. They are absent when the order meets the minimum. A cart that applies such a code answers discount_invalid with the same minimum and shortfall in details. Format amount and currency with formatMoney from @usethrottle/money; see Showing money.

Customer limits

New discounts default to one redemption per customer. Set maxRedemptionsPerCustomer to another positive integer for repeat use, or null for unlimited customer redemptions. Usage is recorded when a discounted cart becomes an order.

One goods code and one free-shipping code per cart
A cart can hold one goods code and one free-shipping code. Applying a valid new code replaces the previous one of the same kind; invalid replacement attempts leave the existing code unchanged. Two goods codes are still refused. To remove one of two, send kind (order or shipping) or code; with both applied and neither sent, removal answers 400 discount_kind_required.

Limit a code to customer groups

Send customerGroupIds (0 to 50 group ids) on create or update to make a code usable only by members of those groups. It needs the customer_groups:read scope (otherwise 403 insufficient_scopes); an unknown group answers 422 customer_group_not_found. Empty or absent means everyone; on update, absent keeps the groups and [] clears them. Responses carry customerGroupLimited, and customerGroupIds for callers with the scope.

  • The group check runs before every other check. A buyer who is not eligible gets the same Discount code not found answer an unknown code gets, so the code stays hidden. The staff validate and preview routes answer the same way.
  • Eligibility needs a customer on the cart, membership of an enabled named group, and proven identity. See Identity proof.
  • Eligibility is judged again on every recalculation, including at checkout. A code whose customer, group or expiry no longer qualifies is dropped silently and totals are recalculated without it.
  • A group that a discount names cannot be deleted (409 customer_group_in_use).

Exclude products from a code

Send conditions.excludedProductIds on create or update to list line identifiers a code never applies to, for example gift card SKUs. Entries match lines the same way conditions.productIds does: the line id, referenceId, sku, productId, variantId, or the same keys in line metadata, trimmed and case-insensitive.

A percentage code that skips gift cards
curl -X POST https://api.usethrottle.dev/api/v1/discounts \
  -H "X-API-Key: sk_live_xxx" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "20% off, not gift cards",
    "code": "SPRING20",
    "type": "percentage",
    "value": 20,
    "conditions": { "excludedProductIds": ["GIFT-25", "GIFT-50"] }
  }'
  • An exclusion wins. A line listed in both productIds and excludedProductIds gets no discount. A code with exclusions and no productIds applies to every other line.
  • A percentage code takes its percentage of the remaining lines only; a fixed-amount code is capped at their total. If every line is excluded, the code computes to 0.
  • Up to 500 strings of up to 200 characters. Blank and duplicate entries are dropped; anything else is 400 validation_error naming the field. On update, an empty array removes the list. Like every conditions write, the object you send replaces the stored one, so send the other keys you want to keep.
  • The order's metadata.discountScope records the exclusions with the product scope, so a line added to the order later is judged by the rule it was placed under.
  • Exclusions are identifiers, not products. In the dashboard, picking a Product Catalog product adds the SKUs of its variants; a variant added to the product later is not excluded until you add it.

List and search codes

GET /api/v1/discounts uses cursor pagination and accepts q, type, isActive, code, and sort filters. Use meta.pagination.cursor for the next page until hasMore is false.

Cart and order records

Applied coupons are visible on cart reads and are preserved on the order snapshot. A cart response includes appliedDiscount with the goods code, discount ID, type, amount, currency, validity, and snapshot hash. When the cart becomes an order, the order stores discountId, discountCode, and metadata.appliedDiscount; a free-shipping code is stored as shippingDiscountId, shippingDiscountCode and shippingDiscountTotal.

Calculated tax is charged on the price after the code: a cart-wide code lowers every line's taxable amount in proportion, and a code limited to certain products lowers only those lines. Native tax, the Avalara quote and the filed Avalara document agree, and the stateless quote nets its discountsTotal the same way. A tax rule set to tax before discounts still taxes the full price. An order with a discount carries metadata.taxDiscountBasis: "net_of_cart_code"; editing its line items re-taxes it the same way. Orders placed before this behaviour shipped have no such key and keep the tax basis they were placed on when edited. The key is managed by Throttle, so do not set or remove it yourself.

The lines a code applied to are recorded on the order when it is placed, as metadata.discountScope (the code, its type and value, its product scope and excluded products, and the order line ids it reduced). Editing the order's line items and the filed Avalara document read that record, not the discount as it is now: narrowing, widening, re-pricing or deleting a code after an order was placed does not change that order's tax. A line added by an edit shares the code when the recorded product scope covers it. Orders placed before this record existed read the live discount, as before. Throttle manages this key too: a value you send is ignored.

Redemption timing
Global and per-customer usage counts are recorded when the discounted cart is converted to an order. Preview does not mutate usage. Apply validates customer limits when the cart has a customer ID.

Payment flow

Throttle applies discounts before payment. The payment processor receives the final amount to authorize or capture; it does not receive a coupon code to validate.

sequenceDiagram
  participant B as Browser
  participant M as Merchant Backend
  participant T as Throttle API
  participant C as Checkout Iframe
  B->>M: buyer enters SUMMER25
  M->>T: POST /api/v1/discounts/preview
  T-->>M: valid + discountTotal + total
  M-->>B: show adjusted order summary
  B->>M: buyer starts checkout
  M->>T: POST /api/v1/carts/{id}/apply-discount
  M->>T: POST /api/v1/checkout/sessions
  M-->>B: sessionId
  B->>C: render checkout
  C->>T: complete payment with discounted total
Discount preview, cart apply, and checkout handoff.

Metadata

Discounts accept arbitrary JSON metadata for campaign IDs, channels, attribution, or merchant notes. Metadata is stored with the discount and returned by the REST API, GraphQL API, and SDK.

Discount metadata
await discounts.create({
  code: 'SUMMER25',
  name: 'Summer 25% off',
  type: 'percentage',
  value: 25,
  maxRedemptionsPerCustomer: 1,
  metadata: {
    campaign: 'summer-2026',
    channel: 'email',
  },
});

const discount = await discounts.get('disc_xxx');
// discount.metadata.campaign === 'summer-2026'

Apply to checkout

Cart application is the authoritative step. Apply the code to a native Throttle cart before you create or render the checkout session.

Cart mutation
// Server-side only. Never expose your sk_ key in the browser.
import { createDiscountsClient } from '@usethrottle/discounts';

const discounts = createDiscountsClient({
  apiKey: process.env.THROTTLE_API_KEY!,
});

await discounts.applyToCart(cartId, 'SUMMER25');

// Remove the active code. With a goods code and a free-shipping code
// applied, name the one to remove:
await discounts.removeFromCart(cartId, { kind: 'shipping' }); // or 'order'
Storefront pattern
// Storefront checkout pattern
// 1. Buyer enters code in your order summary.
// 2. Your server previews it without mutating a cart.
const preview = await discounts.preview({ code, currency: 'USD', subtotal, customerId });

// 3. If valid, include the code when your server creates the Throttle cart.
const cart = await cartClient.carts.create({ applicationId, currency: 'USD' });
await Promise.all(items.map((item) => cartClient.items.add(cart.id, item)));
await discounts.applyToCart(cart.id, preview.code);

// 4. Create the checkout session using the discounted cart id.
await checkout.createSession({ applicationId, cartId: cart.id, returnUrl, cancelUrl });

Pre-applying at session create

POST /api/v1/checkout/sessions accepts a top-level discountCode: string field. When provided, Throttle validates the code synchronously against the session's cart and applies it before returning. The response cart total reflects the discount. Send a free-shipping code as shippingDiscountCode, alongside discountCode: a free-shipping code in discountCode, or a goods code in shippingDiscountCode, answers 400 discount_kind_mismatch.

Pre-apply at session create
curl -X POST https://api.usethrottle.dev/api/v1/checkout/sessions \
  -H "X-API-Key: sk_live_xxx" \
  -H "Content-Type: application/json" \
  -d '{
    "applicationId": "e7efb0a6-892e-46b2-97ab-296bb04c5b29",
    "externalCartId": "cart_abc",
    "amount": 2999,
    "currency": "USD",
    "discountCode": "FRIEND10",
    "shippingDiscountCode": "SHIPFREE"
  }'
Validation is synchronous
An invalid or expired code returns 422 discount_invalid. The session is not created. Your storefront should call /api/v1/discounts/preview first if you want to surface the error inline, then retry the session create with the validated code (or omit it). The preview endpoint computes the discounted total without mutating any cart or session.

Discounts in more than one currency

A discount carries its amounts per currency in amounts, keyed by currency code, in minor units. value is the fixed amount (fixed-amount codes only) and minOrder is the minimum order total.

A fixed-amount code in USD and EUR
curl -X POST https://api.usethrottle.dev/api/v1/discounts \
  -H "X-API-Key: sk_live_xxx" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Welcome 9",
    "code": "WELCOME9",
    "type": "fixed_amount",
    "amounts": {
      "USD": { "value": 1000, "minOrder": 5000 },
      "EUR": { "value": 900,  "minOrder": 4500 }
    }
  }'
  • No entry means not offered. Throttle never converts. A code with no entry for the order's currency answers 422 discount_currency_unsupported ("This code can't be used for orders in GBP.") on every cart kind, and validate returns it as code.
  • Percentage codes with no minimum anywhere keep amounts: {} and work in every currency. A minimum in one currency makes the other currencies need an entry.
  • Legacy writes mean the main currency. value and conditions.minOrder without amounts set the main-currency entry. When both are sent they must agree. A write whose amounts lacks the main currency answers 400 with the path amounts.<MAIN> (or amounts.<MAIN>.minOrder, conditions.minOrder). The minimum applies to fixed-amount codes too.
  • POST /api/v1/discounts/validate and /preview take an optional currency; it defaults to the store's main currency.

Current boundaries

  • Promotion codes work on cart-backed checkout totals.
  • Discounts are order-level cart reductions, not item-level discounts.
  • Only one goods coupon and one free-shipping coupon can be attached to a cart; this is enforced by the API and database.
  • External/provider-owned carts must apply discounts upstream in the provider.
  • Recurring subscription discounts are not part of this v1 surface.
  • Keep secret API keys on your backend; browsers should call your server.
Related guides
Continue with Cart API for native carts and Embedded Checkout for the iframe handoff.