Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 55 ยท Shopify Functions

Building a Function from Scratch

Build a Shopify discount function step by step: generate the extension, write the input query, read merchant settings from a metafield, then run and replay it locally.

In Shopify Functions Overview you learned the contract: input JSON goes in, a list of operations comes out, and nothing else is allowed to happen. This lesson turns that contract into a project. You will generate a function extension, write its input query, implement the logic, let a merchant configure it through a metafield, and exercise it locally with the CLI's run and replay commands.

The running example is a volume discount: when a customer buys at least N of the same item, take P percent off that line. Real CLI commands, TOML, GraphQL and function source are read-only here because they need the Shopify CLI and a dev store. Every concept also has a plain JavaScript stand-in that you can run and edit on this page, and each section says which part is real and which is the stand-in. Code targets API version 2026-07; generate your own extension to see the exact names for the version you use, because templates and target names change between releases.

Step 1: generate the extension

Inside an app created with the CLI (see Creating an App with the CLI), run the generator and pick a discount function template, then JavaScript (or Rust):

Terminal
# read-only: requires the Shopify CLI and a logged-in Partner or Dev Dashboard account
shopify app generate extension --name volume-discount

The CLI asks which kind of extension you want and which language. It creates a folder under extensions/ and registers it for the next shopify app deploy. The files you will touch are the same ones you met in the overview:

TEXT
extensions/volume-discount/
  shopify.extension.toml   # type = "function", targets, API version
  src/
    run.graphql            # input query
    run.js                 # logic: export function run(input)
  locales/en.default.json  # optional strings for merchant-facing text

The extension TOML names the target (where Shopify calls you), the file with the input query and the exported function. Template-generated names differ slightly between versions, for example an export called cartLinesDiscountsGenerateRun rather than run. Whatever the template produced, keep TOML and source in agreement.

TOML
# shopify.extension.toml (read-only sketch)
api_version = "2026-07"

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

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

Step 2: write the input query

The input query is a GraphQL query typed against your target's schema. It decides what your code can see. Select only what you use: smaller inputs run faster and stay within the instruction budget.

GRAPHQL
# src/run.graphql (read-only)
query Input {
  cart {
    lines {
      id
      quantity
      cost {
        amountPerQuantity {
          amount
        }
      }
      merchandise {
        __typename
      }
    }
  }
  discount {
    discountClasses
    metafield(namespace: "$app:volume-discount", key: "config") {
      jsonValue
    }
  }
}

Three details are worth noticing. amount is a decimal string, not a number, so money arithmetic needs care (the stand-ins below convert to integer cents first; see Building a Promotions Engine for why money math avoids floats). merchandise is a union, which is why the query asks for __typename: a cart line can hold something that is not a product variant, and your code should only discount what it understands. And metafield(namespace: "$app:...") uses the app-owned namespace prefix from Metafields and Metaobjects from the API.

After changing the query or API version, regenerate the TypeScript types so the editor knows the shape of input:

Terminal
# read-only
shopify app function typegen

Step 3: configuration through a metafield

A function is one compiled module shared by every shop that installs your app, so "5 items, 10 percent" cannot be hard-coded. The merchant enters those numbers in your app's admin page; your app saves them as JSON in a metafield on the discount; the input query reads that metafield (discount.metafield); the function parses it. The write happens when the discount is created or updated, for example:

GRAPHQL
# read-only: Admin API 2026-07
mutation CreateVolumeDiscount($discount: DiscountAutomaticAppInput!) {
  discountAutomaticAppCreate(automaticAppDiscount: $discount) {
    automaticAppDiscount {
      discountId
    }
    userErrors {
      field
      message
    }
  }
}
JSON
{
  "discount": {
    "title": "Buy 5, save 10%",
    "functionHandle": "volume-discount",
    "startsAt": "2026-08-01T00:00:00Z",
    "discountClasses": ["PRODUCT"],
    "combinesWith": { "orderDiscounts": true, "shippingDiscounts": true, "productDiscounts": false },
    "metafields": [
      {
        "namespace": "$app:volume-discount",
        "key": "config",
        "type": "json",
        "value": "{\"minQuantity\":5,\"percentage\":10}"
      }
    ]
  }
}

Always check userErrors on the response, as described in Mutations and userErrors. The metafield value is a string containing JSON, which is why the quotes are escaped. When the function reads it through jsonValue, Shopify has already parsed it for you.

Because merchants (or bugs) can store anything, never trust the metafield. A function that crashes on null produces no discount, which is safe but looks like a broken app. Validate and fall back to a default.

flowchart LR
    A["Merchant sets<br/>5 items, 10 percent"] --> B["Your app saves JSON<br/>in a discount metafield"]
    B --> C["Checkout runs the<br/>input query"]
    C --> D["Function parses config<br/>and returns operations"]
    D --> E["Shopify applies<br/>the discount"]

Configuration travels as data: the same compiled code behaves differently per shop.

Step 4: the logic as a pure function

Here is the full function, read-only, in the style the JavaScript template produces:

JavaScript
// src/run.js (read-only sketch)
const DEFAULT_CONFIG = { minQuantity: 5, percentage: 10 };

function readConfig(metafield) {
  const raw = metafield?.jsonValue;
  const minQuantity = Number(raw?.minQuantity);
  const percentage = Number(raw?.percentage);
  if (Number.isInteger(minQuantity) && minQuantity >= 2 && percentage > 0 && percentage <= 80) {
    return { minQuantity, percentage };
  }
  return DEFAULT_CONFIG;
}

export function run(input) {
  if (!input.discount.discountClasses.includes("PRODUCT")) {
    return { operations: [] };
  }
  const config = readConfig(input.discount.metafield);
  const targets = input.cart.lines
    .filter((line) => line.merchandise.__typename === "ProductVariant")
    .filter((line) => line.quantity >= config.minQuantity)
    .map((line) => ({ cartLine: { id: line.id } }));

  if (targets.length === 0) {
    return { operations: [] };
  }
  return {
    operations: [
      {
        productDiscountsAdd: {
          candidates: [
            {
              message: `${config.percentage}% off ${config.minQuantity}+`,
              targets,
              value: { percentage: { value: String(config.percentage) } },
            },
          ],
          selectionStrategy: "ALL",
        },
      },
    ],
  };
}

The shape follows three habits you should keep in every function: check that your discount class is enabled, filter to what you can handle, and return an empty operations list whenever there is nothing to do. The percentage value is a string, as in the schema. Now run the same logic live. The stand-in below is not Shopify's runtime, only a plain function with the same input and output, plus a savings calculation (in integer cents) so you can see the effect.

JS A volume-discount function with config fallbacks

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

No output.

The stand-in confirms the habits: bad configuration falls back to defaults, an unknown merchandise type is skipped, and a disabled class returns an empty list without computing anything.

Step 5: run the function locally

The CLI can execute your compiled function against an input file, with no store and no checkout. This is the fastest feedback loop you will have (read-only commands):

Terminal
# read-only: build, then feed the function a JSON input
shopify app function run --path extensions/volume-discount < input.json

The command prints the output JSON together with the function's logs and its instruction count, so you can see how close you are to the budget described in the overview. To run against a real checkout, install the app on a dev store, enable the discount, and use the function runs view (in the Dev Dashboard or the developer console of shopify app dev). Shopify records the input and output of recent runs, and you can re-run one against your current local code:

Terminal
# read-only: pick a recorded run and replay it against your local code
shopify app function replay --path extensions/volume-discount

replay is valuable because it uses the exact input a real cart produced, including fields you did not expect. We cover logs, replay and limits in Testing and Debugging Functions.

The stand-in below mimics the idea: it keeps a "log" of recorded inputs, runs an old and a new version of the logic against all of them, and shows which runs changed. This is also how you should treat any refactor: replay yesterday's inputs, compare outputs.

JS Replay recorded inputs against two versions

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

No output.

Step 6: deploy and attach to a discount

Nothing in the CLI changes a store's discounts. Your next steps (all read-only here) are:

  1. shopify app deploy builds the Wasm module and releases a new app version that includes the function.
  2. Your admin UI creates the discount with discountAutomaticAppCreate (automatic) or discountCodeAppCreate (code-based) and the function's handle, as shown above.
  3. Test in the dev store's checkout and open the function runs view to confirm the input and output.

When the function misbehaves, remember the failure modes: invalid output or an exceeded limit means Shopify ignores the result, so a "discount that does nothing" is a debugging clue, not a mystery. For a complete, polished version of this exact feature see Project: Tiered Volume Discount.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should the 'minimum quantity' setting for a volume discount live?

    The compiled function is shared by all shops, has no network access, and reads per-shop settings from the input. A metafield selected in the input query is the standard way.
  2. 2. Why does the example query ask for merchandise __typename?

    merchandise is a union type. Checking __typename lets the function skip unsupported kinds instead of failing on missing fields.
  3. 3. A merchant saved percentage: 500 in the configuration. What should a well-written function do?

    Never trust configuration. Validate it, and prefer a safe fallback or an empty operations list over a crash or an absurd discount.
  4. 4. What does shopify app function replay do?

    Replay takes the input of a recorded run and executes your current local build on it, which is ideal for debugging and for checking refactors.

Summary

  • Generate a function extension with the CLI; TOML names the target, input query and exported function.
  • The input query selects only the data the logic needs, including the configuration metafield.
  • Configuration is JSON stored in a metafield by your app and parsed defensively by the function.
  • The logic is a pure function: check the discount class, filter, return operations or an empty list.
  • shopify app function run and replay give fast local feedback; shopify app deploy releases the module.
  • Real CLI, TOML and source here are read-only; the TryIts are plain JavaScript stand-ins with the same contract.

Next, go deeper into the discount types themselves: Discount Functions in Depth.