Shopify Discount Function Settings: Build the Admin UI

Shopify discount function settings live in an admin UI extension on the admin.discount-details.function-settings.render target. The extension renders a form inside the discount details page, writes the merchant’s choices to a JSON metafield on the discount with applyMetafieldChange, and the Discount Function reads that metafield on every run. One line in the Function’s TOML links the two.

The bugs sit in the seams between those pieces: the link that is never made, a failed save that nothing checks, and discount classes that the settings page changes but the Function ignores. The code below targets API version 2026-10, which Shopify’s versioning page lists as the latest stable release as of November 2026.

How does the settings extension connect to the Function?

Through the Function’s [extensions.ui] section. You scaffold the settings extension with the CLI template from Shopify’s discount UI tutorial:

shopify app generate extension --template discount_details_function_settings --name volume-discount-ui

That gives you a ui_extension with its own shopify.extension.toml. Its targeting block points the discount settings target at a module:

api_version = "2026-10"

[[extensions]]
name = "t:name"
description = "t:description"
handle = "volume-discount-ui"
type = "ui_extension"

[[extensions.targeting]]
module = "./src/DiscountFunctionSettings.jsx"
target = "admin.discount-details.function-settings.render"

[[extensions.metafields]]
namespace = "$app"
key = "function-configuration"

Then, in the Function’s own shopify.extension.toml, set handle under [extensions.ui] to that extension’s handle:

[extensions.input.variables]
namespace = "$app"
key = "function-configuration"

[extensions.ui]
handle = "volume-discount-ui"

Skip that and the extension still builds and deploys. It just never appears on the discount page, because the admin has no idea which Function it configures. With the link in place, the tutorial says Shopify lists your discount in the discount type picker. It also registers a shopify/Discount intent, so Sidekick and the admin can create and edit the discount with no extra work from you.

The tutorial also declares the configuration metafield in the UI extension’s TOML with [[extensions.metafields]], as above. If shopify.data.metafields comes back empty on a discount you know has settings, check that block before anything else.

What does the settings form look like?

The root element has to be s-function-settings. The function settings target reference says this component hooks into the admin’s native save bar, and that it requires an onReset handler. You do not render your own Save button. The merchant edits fields, the save bar appears, and pressing Save fires your submit handler.

Here is a complete module for a volume discount with a percentage and a minimum quantity, stored as one JSON metafield:

import {render} from 'preact';
import {useState} from 'preact/hooks';

const NAMESPACE = '$app';
const KEY = 'function-configuration';
const DEFAULTS = {percentage: 10, minQuantity: 2};

export default async () => {
  render(<Extension />, document.body);
};

function readConfig() {
  const field = shopify.data.metafields.find((m) => m.key === KEY);
  if (!field) return DEFAULTS;
  try {
    return {...DEFAULTS, ...JSON.parse(field.value)};
  } catch {
    return DEFAULTS;
  }
}

function Extension() {
  const [saved, setSaved] = useState(readConfig);
  const [percentage, setPercentage] = useState(String(saved.percentage));
  const [minQuantity, setMinQuantity] = useState(String(saved.minQuantity));
  const [classes, setClasses] = useState(shopify.discounts.discountClasses.value);
  const [error, setError] = useState();

  async function save() {
    const next = {
      percentage: Number(percentage),
      minQuantity: Number(minQuantity),
    };
    const result = await shopify.applyMetafieldChange({
      type: 'updateMetafield',
      namespace: NAMESPACE,
      key: KEY,
      value: JSON.stringify(next),
      valueType: 'json',
    });
    if (result.type === 'error') {
      setError(result.message);
      throw new Error(result.message);
    }
    setError(undefined);
    setSaved(next);
  }

  function reset() {
    setPercentage(String(saved.percentage));
    setMinQuantity(String(saved.minQuantity));
    setError(undefined);
  }

  async function toggleClass(name) {
    const next = classes.includes(name)
      ? classes.filter((c) => c !== name)
      : [...classes, name];
    const result = await shopify.discounts.updateDiscountClasses(next);
    if (result.success) {
      setClasses(result.value);
    } else {
      setError('Could not update the discount classes.');
    }
  }

  return (
    <s-function-settings
      onSubmit={(event) => event.waitUntil(save())}
      onReset={reset}
    >
      <s-section heading="Volume discount">
        <s-stack gap="base">
          {error ? <s-banner tone="critical">{error}</s-banner> : null}
          <s-number-field
            label="Discount"
            suffix="%"
            min={0}
            max={100}
            value={percentage}
            onChange={(event) => setPercentage(event.currentTarget.value)}
          />
          <s-number-field
            label="Minimum quantity per line"
            min={1}
            step={1}
            value={minQuantity}
            onChange={(event) => setMinQuantity(event.currentTarget.value)}
          />
          <s-checkbox
            label="Discount products"
            checked={classes.includes('product')}
            disabled={classes.length === 1 && classes.includes('product')}
            onChange={() => toggleClass('product')}
          />
          <s-checkbox
            label="Discount the order subtotal"
            checked={classes.includes('order')}
            disabled={classes.length === 1 && classes.includes('order')}
            onChange={() => toggleClass('order')}
          />
        </s-stack>
      </s-section>
    </s-function-settings>
  );
}

We match the metafield on key alone, which is what Shopify’s own tutorial does. The parse sits in a try because the first time a merchant opens a new discount there is no metafield yet, and a hand-edited one can hold anything.

Why check what applyMetafieldChange returns?

Because applyMetafieldChange does not reject when the write fails. Per the Discount Function Settings API reference, it resolves with a MetafieldChangeResult, which is either {type: 'success'} or {type: 'error', message}. Await it, ignore the result, and your submit promise resolves whether or not the write happened.

The function settings component reference describes waitUntil as taking a promise that signals “the duration and eventual success or failure” of the submit. So the module above throws on type: 'error'. That turns a failed write into a rejected promise, which is the signal waitUntil is waiting for, and it puts the message in a banner where the merchant can read it.

The same reference has a timing rule that catches people out: waitUntil can be called more than once, but only synchronously during the event dispatch. Not after a setTimeout, not inside a microtask. Call it first thing in onSubmit with the whole save promise, as above. If you await something and then call waitUntil, you have already missed the window.

Two other details from that API reference. namespace is optional on an update and gets a default if you leave it out, but naming $app keeps the extension and the Function’s TOML visibly in step. And valueType is optional on updates to an existing metafield, but the first write creates it, so pass json every time rather than relying on whichever code path ran first.

How do discount classes work in the settings UI?

shopify.discounts gives you the discount’s classes as a signal (discountClasses) and a setter (updateDiscountClasses). The classes are product, order and shipping. The setter returns a result object: {success: true, value} or {success: false, errors}. The module copies result.value into local state so the checkboxes reflect what the admin accepted, not what was requested.

The tutorial disables the last ticked checkbox so a discount can never be left with zero classes, and we do the same.

Changing classes in the UI only matters if the Function honours them. Read discountClasses in the input query and return operations only for the classes the discount carries. This query validates against the 2026-10 Discount Function API:

query CartLinesDiscountsGenerateRunInput {
  cart {
    lines {
      id
      quantity
    }
  }
  discount {
    discountClasses
    metafield(namespace: "$app", key: "function-configuration") {
      jsonValue
    }
  }
}

jsonValue hands the Function the parsed object, so there is no string parsing on the Function side. If your configuration includes ids the Function should filter on, such as collections, move them into input variables instead; our post on Function input query variables covers that wiring, and the [extensions.input.variables] block in the TOML above already points at the same metafield.

Keep the JSON small. Input queries do not return metafields over 10,000 bytes, a limit we went through in our discount Function API migration guide. A settings page that lets merchants paste a long list of SKUs will eventually write a value the Function cannot see, and the Function then runs as if it had no configuration at all.

What permissions and definitions does the app need?

The tutorial’s app asks for write_discounts, plus read_products because its form looks up collections. It also declares the configuration metafield as an app-owned definition in shopify.app.toml, under [discount.metafields.app.function-configuration] with type = "json". Declaring definitions in TOML means they deploy with the app; our write-up on metafield definitions in TOML has the details of that format.

What we would build

For any discount a merchant will tune more than once, we build the settings extension on day one. One $app JSON metafield, s-function-settings as the root, waitUntil called synchronously with a promise that rejects on type: 'error', and a Function that reads both the metafield and discountClasses.

We would skip the extension when the discount is a one-off for a single store and the numbers will never change. Hard-code them in the Function, ship it, and save the form for when a second merchant wants different numbers.

Whoooop builds Shopify Functions and the admin extensions that configure them, including the settings pages merchants use to change a discount without asking for a deploy. Our Shopify development work covers both halves, the Function and the form.

Need this built properly?

Get in touch

Hack the planet!