Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 55 ยท Shopify Functions

Shopify Functions Overview

Learn what Shopify Functions are, which function APIs exist (discounts, delivery, payment, validation, cart transform), the input and output model and the Wasm sandbox.

Every shop has rules that are specific to its business: "10% off when you buy five of the same item", "hide cash on delivery for large orders", "do not allow more than two gift cards in a cart". For years, merchants on the highest plan wrote such rules in Ruby with Shopify Scripts, and everybody else used apps that called back to a server during checkout. Neither approach scaled well: scripts were limited to one plan and one language, and a server in the middle of checkout adds latency and a point of failure.

Shopify Functions replace both with a different idea. You write a small piece of logic, you compile it to WebAssembly, and you upload it to Shopify. Shopify then runs it on its own infrastructure, inside checkout, in a few milliseconds, with no network call to your server. A function is installed by your app and configured by the merchant, so one app can serve thousands of shops.

This lesson explains what functions are, which kinds exist, how data flows in and out, and what the sandbox forbids. Building one comes next in Building a Function from Scratch. The real function code and CLI commands here are read-only (they need the Shopify CLI and a store); the live examples are plain JavaScript stand-ins that model the input and output idea. API shapes change between versions, so the snippets state the version they follow and you should always generate the schema for your own version.

The model: input in, operations out

A function does not edit the cart. It is a pure transformation:

  1. Shopify runs the input query, a GraphQL query you wrote that selects the data you need (cart lines, buyer, shop metafields, and so on). The result is a JSON document.
  2. Shopify hands that JSON to your compiled code.
  3. Your code returns a JSON document of operations: instructions such as "apply 10% to these lines" or "hide this payment method".
  4. Shopify validates the output and applies it.
flowchart LR
    A["Checkout event"] --> B["Run input query<br/>(GraphQL)"]
    B --> C["Function (Wasm)<br/>input JSON in"]
    C --> D["Operations JSON out"]
    D --> E["Shopify applies<br/>and validates"]
    E --> F["Buyer sees the result"]

Shopify controls both ends: you choose the query and the logic, never the side effects.

Because the function is only a mapping from data to data, it is easy to test, easy to replay and safe to run in a tight sandbox. If the function crashes, times out or returns something invalid, Shopify ignores its output instead of breaking checkout (what exactly happens differs by function type, so read the reference for yours).

The function APIs

Each function is written against one API, which defines its input type and the operations it may return. The list below names the families you will meet most. Names and the set of APIs grow over time, so use it as a map and check the current list when you generate an extension.

API family What it can do Typical use
Discount Add product, order or delivery discounts Volume pricing, "spend X save Y", free shipping rules
Cart transform Merge, expand or update cart lines Bundles, "build a kit", custom line titles and prices
Delivery customization Hide, rename or reorder delivery options Hide express to remote areas
Payment customization Hide, rename or reorder payment methods Hide cash on delivery above a limit
Cart and checkout validation Return errors that block progress Quantity limits, address rules, age-restricted items
Fulfillment and order routing Constrain or rank fulfillment locations Ship oversized items only from some warehouses

Discounts and validation are covered in depth in Discount Functions in Depth and Cart Validation, Delivery and Payment Customization. The price rules behind discount functions are explained, independent of Shopify, in Building a Promotions Engine.

What a function project looks like

You create a function by generating an extension with the CLI. The folder contains a configuration file, the input query and your code (read-only sketch, details vary by template and version):

TEXT
extensions/volume-discount/
  shopify.extension.toml     # name, type = "function", API version, targets
  src/
    run.graphql              # the input query
    run.js                   # your logic (or src/main.rs for Rust)
  package.json
TOML
# shopify.extension.toml (read-only sketch)
api_version = "2025-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"

A target is the exact moment in checkout where Shopify calls you; for example, discounts that apply to the cart are generated at a target whose name ends in discounts.generate.run. The input query is typed against that target's schema, so Shopify can tell at deploy time whether you asked for fields that do not exist.

A minimal query and logic, again read-only:

GRAPHQL
# src/run.graphql
query Input {
  cart {
    lines {
      id
      quantity
    }
  }
  discount {
    discountClasses
  }
}
JavaScript
// src/run.js (read-only sketch)
export function run(input) {
  const total = input.cart.lines.reduce((n, line) => n + line.quantity, 0);
  if (total < 5) {
    return { operations: [] };
  }
  return {
    operations: [
      {
        productDiscountsAdd: {
          candidates: [
            {
              message: "10% off for 5 or more",
              targets: input.cart.lines.map((line) => ({ cartLine: { id: line.id } })),
              value: { percentage: { value: "10" } },
            },
          ],
          selectionStrategy: "ALL",
        },
      },
    ],
  };
}

Notice two things. The function only sees the fields the query asked for, so asking for less makes it faster and smaller. And the output is plain data: { operations: [] } means "do nothing", which is the correct answer for most carts most of the time.

JavaScript, Rust and WebAssembly

Shopify runs WebAssembly modules. You can write them in any language that compiles to Wasm, but the CLI templates focus on two:

  • JavaScript or TypeScript. The toolchain bundles your code with a small JavaScript engine compiled to Wasm, so it feels like normal Node-style code. It is the quickest way to start, with a larger module and more instructions used per run.
  • Rust. Compiles to a small, fast module, which matters when the logic is heavy or the cart is large.

The choice only changes how you write the logic. The input and output JSON are identical, which is why this course's examples are plain JavaScript functions you can run and test anywhere.

The sandbox and its limits

Functions are fast and safe because they are boxed in:

  • No network. A function cannot call your server or any API from inside its run. Everything it needs must be in the input query or in a metafield the merchant configured. (A separate "fetch" capability exists for a few function types with different rules; it is outside this lesson.)
  • No clock or randomness you can rely on, and no state. Two runs with the same input should give the same output. Do not read the system time or keep data between runs.
  • Strict budgets. Documented limits include roughly 11 million Wasm instructions per run and a module size of about 256 KB, along with caps on input and output size. Check the current numbers in the reference; see Testing and Debugging Functions for how to watch them.
  • Deterministic output only. The output must match the API's schema. Extra or misspelled fields cause the run to be rejected.

Configuration therefore lives outside the code. A merchant sets "tiers" or "blocked countries" in your app's admin page, your app saves them as a metafield on the discount or function owner, and the input query selects that metafield so your logic can read it. You will build exactly that in the next lesson.

Stand-in: a function runner

The first stand-in shows the shape of the contract. A runFunction helper freezes the input (so a function cannot mutate it), runs your logic, and checks that the output is a JSON-safe object with an operations array, which is the kind of validation Shopify performs on the real output.

JS The function contract: input in, operations out

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

No output.

The mutating function fails because the frozen input refuses changes, which mirrors the rule that functions return instructions instead of editing data.

Stand-in: the checkout pipeline

Several functions can be active in one checkout, each at its own target. The next stand-in builds a registry that maps target names to functions and runs them in a fixed order against a cart. Targets and order are simplified; the point is to see that every function is independent, receives only its own input and returns only operations.

JS A registry of functions at different targets

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

No output.

In the real platform, the target names, input fields and operation shapes are fixed by the API you generate against; the stand-in uses invented shapes to keep the example short.

When not to use a function

Functions are not a place for everything. If you need data from your own database at checkout time, the right pattern is to precompute it into a metafield when it changes (for example through a webhook handler, see Reliable Webhook Handlers) rather than to fetch it during the run. If you need to change what a customer sees in the checkout UI, that is a checkout UI extension. And if a rule needs to charge or refund money, it belongs in the order and payment flows, not in a function, which can only shape price, options and validation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a Shopify Function return?

    A function maps an input JSON document to an output JSON document of operations. Shopify validates the output against the API schema and applies it.
  2. 2. Why can a function not call your own server during a run?

    The sandbox has no network by design. Data comes from the input query or from metafields that your app wrote earlier.
  3. 3. Where should a merchant-specific setting such as discount tiers live?

    Functions are compiled and shared by all shops. Per-shop settings are stored in metafields, read through the input query, so the code stays the same for everyone.
  4. 4. Which statement about the function language is correct?

    Shopify runs Wasm modules. JavaScript and Rust are the common choices, and both read the same input JSON and return the same operation JSON.

Summary

  • A function is a compiled WebAssembly module that Shopify runs inside checkout; it maps input JSON to a list of operations and has no side effects.
  • You write an input query in GraphQL and logic in JavaScript or Rust; a target names the moment where Shopify calls you.
  • Function APIs include discounts, cart transform, delivery and payment customization, validation and fulfillment routing.
  • The sandbox forbids network access and state; budgets for instructions and module size apply.
  • Per-shop configuration lives in metafields that the input query selects.

Next, build one yourself: Building a Function from Scratch.