Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 55 ยท Real-World Projects

Project: Tiered Volume Discount

Build a tiered volume discount for Shopify: function configuration in a metafield, input query, tier math in integer cents, an admin UI and runnable tests.

"Buy 3, save 5%. Buy 6, save 10%. Buy 12, save 15%." Volume discounts are one of the most requested pricing features, and they are a perfect fit for a Shopify Function: the rule runs inside checkout, it must be fast and deterministic, and the merchant needs to change the numbers without calling you. In this project you build the whole feature: a function that reads tiers from configuration, an admin page where the merchant edits them, and tests that prove the maths.

As in the other project lessons, the real app code (TOML, GraphQL, the function entry point, the admin route) is read-only: this site cannot run Shopify. The tier maths is plain JavaScript with no Shopify imports, and that part is a runnable stand-in: you feed it a hand-made cart, exactly the shape a function receives, and it returns exactly the shape a function must return. The examples follow the discount function API as it looks in recent API versions (this lesson targets 2026-07). Shopify revises function APIs often, so compare the target names and output fields with the current documentation before you ship. If functions are new to you, start with Shopify Functions Overview and Building a Function from Scratch.

The plan

Decide the behaviour before you write code. Our rules:

  1. The merchant defines up to five tiers: a minimum quantity and a percentage off.
  2. The discount applies per product: the quantities of all variants of the same product are added together (3 small + 3 large shirts count as 6 shirts).
  3. Only the best matching tier applies; tiers do not stack.
  4. Optionally the merchant limits the discount to products in a list of product ids. An empty list means all products.
  5. The function never throws on bad configuration; it simply returns no discount.

Rule 5 matters. A function that crashes can block checkout. Treat configuration as untrusted input, even if your own admin page wrote it, because a merchant can edit metafields in other ways.

flowchart LR
    M["Merchant<br/>admin page"] -->|"metafieldsSet"| C["Discount metafield<br/>(tiers JSON)"]
    C --> Q["Input query result"]
    Cart["Cart lines"] --> Q
    Q --> F["Function run<br/>(WebAssembly)"]
    F --> O["Output operations<br/>(candidates)"]
    O --> Co["Checkout applies<br/>the discount"]

Configuration travels through a metafield; the function itself stays pure: input in, operations out.

Configuration and the input query

The merchant's tiers live on the discount itself, in an app-owned metafield. The function declares which data it needs in an input query (a .graphql file next to the function). Shopify runs that query and passes the result as the function's input. Nothing else is available; a function cannot make network calls.

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

[[extensions]]
name = "Volume discount"
handle = "volume-discount"
type = "function"

  [[extensions.targeting]]
  target = "cart.lines.discounts.generate.run"
  input_query = "src/cart_lines_discounts_generate_run.graphql"
  export = "cart-lines-discounts-generate-run"

  [extensions.build]
  command = ""
  path = "dist/function.wasm"
GRAPHQL
# src/cart_lines_discounts_generate_run.graphql (read-only)
query Input {
  cart {
    lines {
      id
      quantity
      merchandise {
        __typename
        ... on ProductVariant {
          product {
            id
          }
        }
      }
    }
  }
  discount {
    metafield(namespace: "$app", key: "volume-tiers") {
      jsonValue
    }
  }
}

The $app prefix expands to your app's reserved namespace, so other apps cannot overwrite your configuration. The stored value is JSON such as {"tiers":[{"minQuantity":3,"percent":5},{"minQuantity":6,"percent":10}],"productIds":[]}. The field jsonValue returns it already parsed.

Note what is not in the query: prices. A percentage discount does not need them, because the platform applies the percentage to each targeted line. Ask only for fields you use; a smaller query is faster and keeps you inside the function's instruction budget (see Testing and Debugging Functions).

The function

The entry point is thin. It calls a pure function and wraps the result in the operation shape. Below is the real TypeScript file (read-only), and after it the same logic as a runnable stand-in.

TypeScript
// src/cart_lines_discounts_generate_run.ts (read-only)
import { run as tierRun } from "./tiers"; // pure logic, no Shopify imports

export function cartLinesDiscountsGenerateRun(input: Input): CartLinesDiscountsGenerateRunResult {
  return tierRun(input);
}

The platform expects a list of operations. For product discounts the operation is productDiscountsAdd, holding a list of candidates. Each candidate has a message shown to the buyer, one or more targets (cart lines), and a value (here a percentage). A selectionStrategy of FIRST tells Shopify to apply the first candidate that is allowed to apply; ALL applies all candidates, and we use it because each product gets its own candidate.

Node.js The tier maths as a pure function

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.

Three details deserve a second look. The tiers are sorted from the largest threshold down, so find returns the best tier the group reaches, which is rule 3. Lines of the same product share one candidate, which is rule 2. And invalid tiers (a negative percent, a minimum quantity of 1, text instead of numbers) are filtered out silently, which is rule 5. The last two console.log lines show that unreadable configuration produces an empty list of operations, which means "no discount", never an error.

What about money?

We never computed a price: the percentage is applied by Shopify, in the shop's currency, with its own rounding. If you ever need a fixed amount off, calculate in the smallest currency unit with integers, never with floating point numbers, and distribute the remainder across lines deliberately. The reasons are explained in Money as Integers, and the stacking rules between several discounts are in Promotions Engine.

Tests that protect the rules

A function is the ideal thing to unit test: pure input, pure output. Write the tests before the merchant finds the edge cases. The most valuable cases are the boundaries (exactly at a threshold, one below), the combination case (two variants of one product), and the hostile configuration.

Node.js A tiny test harness for the tiers

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 last test is wrong on purpose, so you can see what a failure report looks like. In a real project you would write these tests with your test runner (Vitest is common in the app template) and run them on every commit. For the surrounding workflow, including shopify app function run with sample input files, see Testing and Debugging Functions.

The admin configuration page

Merchants need a form. The app's embedded admin route (React Router, as in the CLI template) does three things: loads the current tiers, validates the submitted ones, and saves them with the Admin API. The sketch below is read-only. The mutation names are current at the time of writing, but check them when you build: discount mutations have been reorganised more than once.

TypeScript
// app/routes/app.volume-discount.$id.tsx (read-only sketch)
export async function action({ request, params }: ActionFunctionArgs) {
  const { admin } = await authenticate.admin(request);
  const form = await request.formData();
  const tiers = JSON.parse(String(form.get("tiers")));

  const problems = validateTiers(tiers); // same rules as the function, plus friendly messages
  if (problems.length > 0) return { problems };

  const response = await admin.graphql(
    `#graphql
    mutation Save($id: ID!, $metafields: [MetafieldsSetInput!]!) {
      metafieldsSet(metafields: $metafields) {
        userErrors { field message }
      }
    }`,
    { variables: { metafields: [{
        ownerId: params.id, namespace: "$app", key: "volume-tiers",
        type: "json", value: JSON.stringify({ tiers, productIds: [] }),
    }] } },
  );
  const json = await response.json();
  return { problems: json.data.metafieldsSet.userErrors.map((e: { message: string }) => e.message) };
}

Two things to notice. First, the page validates with friendly messages ("Tier 2 must start above tier 1"), while the function only protects itself by ignoring bad data; both are needed. Second, userErrors is always checked, as taught in Mutations and userErrors. The discount itself (its title, dates and which function it uses) is created with a discount mutation or in the admin's Discounts page, depending on how you want merchants to start; the metafield approach lets one function serve many differently configured discounts.

The $app prefix is written differently in different places: $app:key in some inputs and namespace: "$app" in others. If a metafield read or write fails, check the exact form the current documentation shows for that field.

Ship checklist

  • The function builds and its output matches the schema (shopify app function schema and shopify app function run with a sample input).
  • Tests cover thresholds, grouping and hostile configuration.
  • The admin page rejects bad tiers, and the function ignores them anyway.
  • A discount is created with the function, and a real checkout in a development store shows the message.
  • Scopes include write_discounts (and read access for any other data you query).
  • You tried a cart with 100 lines, to see the function stay inside its limits.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the function return an empty list of operations when the configuration is unreadable?

    A crashing or failing function can disturb the buyer's checkout. Treat configuration as untrusted input and degrade to 'no discount'.
  2. 2. Where does the function get the merchant's tiers from?

    Functions run in a sandbox without network access. Everything they know arrives through the input query, and configuration is usually stored in a metafield.
  3. 3. A cart holds 3 small and 3 large shirts, and the tiers are 3 -> 5% and 6 -> 10%. What does our rule give?

    Rule 2 groups variants by product, so 6 shirts reach the second tier. Tiers do not stack, so the result is 10%.
  4. 4. Why sort the tiers from the highest minimum quantity down?

    With the largest threshold first, the first tier that satisfies quantity >= minQuantity is the best one. The merchant's order of entry then does not matter.

Summary

  • A volume discount is a pure function: cart and tiers in, discount candidates out.
  • Store merchant configuration in an app-owned metafield and request it in the input query.
  • Group by product, choose the best tier, ignore invalid tiers, and never throw on bad data.
  • Keep the maths in a plain module so it can be unit tested without Shopify.
  • Validate in the admin page with friendly messages, and check userErrors on save.

Next, move from pricing to the checkout page itself with Project: Checkout Upsell Extension.