# Add a Discount Function to a Shopify App

Yes. An agent scaffolds a TypeScript discount function from Shopify's template, writes its input query and logic, runs its Vitest suite and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-discount-function/shopify-app/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the app before it adds an extension, because a function lives inside the app's own configuration and build. In an app started from Shopify/shopify-app-template-react-router, `shopify.app.toml` sets `scopes = "write_products"`, a `[webhooks]` table with `api_version = "2026-10"` and subscriptions for `app/uninstalled` and `app/scopes_update`, and an `[events]` table with a product price-change subscription. `package.json` has `"type": "module"`, `engines.node >= 22.12`, a `workspaces` entry for `extensions/*`, and scripts that wrap the Shopify CLI: `generate` is `shopify app generate`, `deploy` is `shopify app deploy`, `dev` is `shopify app dev`. `app/shopify.server.ts` builds the app with `ApiVersion.October26` and Prisma session storage. `extensions/` holds only a `.gitkeep`. `.github/workflows/ci.yml` installs with npm, yarn and pnpm on Node 22 and 24, type-checks with `tsc --noEmit`, lints, validates Prisma and builds. `AGENTS.md` points coding agents at the Shopify AI Toolkit for platform work and says not to add tooling to the repository.

Shopify's CLI generates a discount function from a template, and the agent reads that template in Shopify/function-examples rather than guessing its shape: `discounts/javascript/discount/default/` renders, for the `typescript` flavor, a `shopify.extension.toml` with `type = "function"`, two `[[extensions.targeting]]` tables, `cart.lines.discounts.generate.run` with `input_query = "src/cart_lines_discounts_generate_run.graphql"` and `cart.delivery-options.discounts.generate.run` with its own query, an `[extensions.build]` table whose `path` is `dist/function.wasm`, a `package.json` whose scripts call `shopify app function typegen`, `shopify app function build` and `shopify app function run`, with `vitest` for `test` and `@shopify/shopify_function` as the dependency, a `schema.graphql` for the function API, and `src/index.ts` re-exporting the two run files. The generated `cart_lines_discounts_generate_run.ts` reads `input.discount.discountClasses`, returns no operations when neither `DiscountClass.Order` nor `DiscountClass.Product` is present, and otherwise emits `orderDiscountsAdd` and `productDiscountsAdd` operations with candidates, targets, a percentage value and a selection strategy; a Vitest file beside it covers the four class combinations.

The agent runs `shopify app generate extension --template discount --flavor typescript --name volume-discount` in its sandbox, which needs the CLI signed in to a Partner account the sandbox does not have, so when that fails it writes the same files by hand from the template, leaving `uid` for the reader's first `shopify app dev` or `shopify app deploy` to fill in, and says so. It then replaces the sample logic with the rule the issue asks for: the input query adds `quantity` and the merchandise's product id to each cart line, the run function groups lines by product and returns one `productDiscountsAdd` candidate per line whose quantity meets a threshold, with the percentage and threshold read from a metafield on the discount node that the query also selects, and the delivery-options target returns an empty operation list. The tests are rewritten for that rule: a cart under the threshold yields no operation, a cart at it yields one candidate targeting the right line, a missing metafield yields nothing, and the `SHIPPING` class alone yields nothing.

Then the agent runs what the extension's own scripts run: `npm install` at the app root so the workspace links the extension, `shopify app function typegen` to regenerate `generated/api.ts` from the schema and the queries, `npm test` for Vitest in the extension directory, and `shopify app function build`, which compiles the TypeScript to WebAssembly and fails on an unsupported API; the JavaScript functions documentation says the event loop is disabled and `fetch`, `setTimeout` and Node globals are unavailable, so the agent keeps the logic synchronous and dependency-free. It adds the extension to the root `ci.yml` as one more step, `npm test --workspace extensions/volume-discount`, and writes the `discountAutomaticAppCreate` mutation the reader runs once in GraphiQL, with `functionHandle` set to the extension's handle and `discountClasses` of `[PRODUCT]`, into the pull request along with the metafield definition the function reads.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add a Shopify Functions discount extension to this app in TypeScript. Read shopify.app.toml, package.json, app/shopify.server.ts, the extensions directory, .github/workflows/ci.yml and AGENTS.md first. Try shopify app generate extension --template discount --flavor typescript; if the CLI cannot sign in, create the same files by hand from Shopify's discount function template: shopify.extension.toml with the two discount targets, package.json with typegen, build, preview and test scripts, schema.graphql, the input queries, src/index.ts and the two run modules. Implement a volume discount: a percentage off each cart line whose quantity reaches a threshold, both read from a metafield on the discount; return no operations for classes the discount does not have. Write Vitest tests for under-threshold, at-threshold, missing metafield and shipping-only cases. Run npm install, shopify app function typegen, the tests and shopify app function build, keep the output, and add the extension's tests to ci.yml. Open a pull request that also lists the discountAutomaticAppCreate mutation and the metafield definition the reader must create.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request adds `extensions/volume-discount/` with `shopify.extension.toml`, `package.json`, `schema.graphql`, `src/index.ts`, the two run modules and their `.graphql` input queries, the Vitest files and a `locales/en.default.json`, and changes `ci.yml` and `package-lock.json`. Its description quotes the Vitest output, the `shopify app function build` result with the path of the produced `function.wasm`, the `discountAutomaticAppCreate` mutation with the function handle filled in, and the metafield namespace and key the function reads. The app's routes, `shopify.app.toml` scopes and webhooks are unchanged, since a function needs none of them to run.

A reviewer checks the discount rule against what the issue asked for, the `discountClasses` the discount should carry when created, and whether the percentage and threshold should come from a metafield, as written, or from a configuration page in the app, which the pull request leaves as a follow-up. The reader's steps are the ones the sandbox cannot do: `shopify app deploy` to register the function with their app, running the mutation on a development store, and placing a test order that crosses the threshold.

## Run it on every Linear issue labelled discount-function

An automation in the Project that holds the app takes a `linear` trigger on `linear.issue.labeled` with the label `discount-function`. Its runs are read-only, so the saved prompt asks for a plan: the run reads `shopify.app.toml`, the existing extensions and the issue's description of the rule, and posts a comment on the issue with the targets it would declare, the input query fields, the metafield shape and the test cases. A handler on the team's server starts the run that writes the pull request, sending this body with the issue's URL in `resources` and a `request_id` that is a UUID v5 of the issue id, so a retried start returns the run already started.

Each rule gets its own extension directory and its own pull request, so an app that ends up with a volume discount, a bundle discount and a free-shipping rule has three functions a reviewer can read separately.

## Why run it on Rush?

A function is only known to work once its tests pass and the WebAssembly build succeeds, and the build is where an innocent `await` or a library call fails. The agent runs `typegen`, the Vitest suite and `shopify app function build` in its own sandbox and keeps every command and its output in the run's record, so the pull request shows a function that compiles and passes its tests rather than source that looks right.

The files come from Shopify's own template, read from its repository, and the rule is written against the generated types, so a field the input query does not select is a compile error. The remaining steps, deploying and creating the discount, are named for the reader with the exact mutation, because they need the reader's Partner account. Three rules for one app, or one rule for three apps, run as separate sessions with separate pull requests.

## Frequently asked questions

### Why TypeScript rather than Rust?

Because the app is a Node project and the template ships a `typescript` flavor with the same targets, tests and scripts, so the function sits in the existing workspace and CI. Shopify's documentation recommends Rust for the best performance and warns that JavaScript hits instruction limits sooner; the pull request says so, and a Rust rewrite later keeps the same `shopify.extension.toml` targets.

### Can the function call my app's API or a database?

No. The JavaScript functions documentation says the event loop is disabled, so promises and `async` code fail at execution, and `fetch`, timers and Node globals are unavailable. Everything the function needs comes in through its input query, which is why the percentage and threshold are read from a metafield on the discount.

### Does this change my app's access scopes?

No. `shopify.app.toml` keeps `write_products`, and the function's input is supplied by Shopify at checkout rather than fetched by the app. Creating the discount through `discountAutomaticAppCreate` needs the discounts scope on the token you run it with, which the pull request notes.

### How do I test it on a real cart?

Run `shopify app deploy` so Shopify registers the function, run the `discountAutomaticAppCreate` mutation from the pull request on a development store, set the metafield, then add enough of one product to a cart to cross the threshold. The run cannot do these steps because they need your Partner account.

### Will CI run the function's tests?

Yes. The pull request adds one step to the existing `ci.yml` that runs the extension's Vitest suite through its workspace, so a change to the rule is checked on every push, alongside the app's own type check, lint and build.

## More Shopify app jobs

- [Add Lint, Type Check and Build Steps to CI for a Shopify App](https://getrush.ai/run/add-lint-to-ci/shopify-app/)
- [Add Order Webhooks to a Shopify App](https://getrush.ai/run/add-order-webhooks/shopify-app/)
- [Add Retry Logic for Throttled Shopify Admin API Calls](https://getrush.ai/run/add-retry-logic/shopify-app/)

## More jobs like this: Turn a Linear label into a PR

- [Add a Dead Letter Queue to a Lambda in AWS CDK from a Linear Issue](https://getrush.ai/run/add-dlq/aws-cdk/)
- [Add Doxygen API Docs to a CMake C++ Library](https://getrush.ai/run/add-doxygen-docs/cmake/)
- [Add a --dry-run Flag to a Click CLI](https://getrush.ai/run/add-dry-run-flag/click/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
