Delivery Customization Function API

Use the Delivery Customization Function API to customize delivery options in checkout.


Delivery Customization Function API

A delivery customization enables you to rename, sort, and hide the delivery options available to customers during checkout. Examples of delivery options include shipping carriers, local delivery, or pickup options. To customize delivery options in checkout, you can only use the Delivery Customization Function API.

Shopify Functions enable you to customize Shopify's backend logic. The Delivery Customization API integrates this logic into the checkout flow.

Use the API to display unique delivery options to customers, with associated data such as buyer identity, delivery groups, delivery addresses, and cost.

Note:

You can activate a maximum of 25 delivery customization functions on each store.

Use cases

  • Hide delivery options for certain products or customers.
  • Reorder delivery options according to user preference.
  • Hide delivery options for PO Box addresses.
  • Add messaging to delivery option titles.

Caution:

Hiding delivery options for PO Box addresses is only supported for delivery options provided by carrier services or third-party shipping apps. If your store uses Shopify's built-in shipping rates, then the address data that's required to detect a PO Box might not be available to your function.

Function target

Checkout

Function Target

Compatibility with Shopify surfaces Supported (4) Partially supported (1) Unsupported (9)


Getting started

Scaffolding the function using Shopify CLI will automatically configure your TOML file. You can alter the default configuration to customize the way your function operates.

Terminal

shopify app generate extension --template delivery_customization

Tutorial - Build a Delivery Customization Function


Targets

A target is an identifier in shopify.extension.toml that specifies where you're injecting code into Shopify Function APIs, or other parts of the Shopify platform. Each target is composed of three to four namespaces. The name begins with a broad Shopify context and ends with the behavior of the extensible element.


Run target

cart.delivery-options.transform.run

The run target renames, sorts, and hides delivery options that are available to customers at checkout, using Shopify data or hardcoded values. The target returns a list of operations to be applied to delivery options.

For example, you might use this to hide a "Same-Day Delivery" option for B2B customers.

Note:

Checkouts and orders can include multiple delivery methods, such as shipping and pickup in the same order. When your app uses delivery or fulfillment data, iterate over all delivery groups or fulfillment orders to determine the delivery method for each one. Don't assume one method for the order. For more information, refer to split carts in checkout.

  • Input

    OBJECT

    The Input object is the complete GraphQL schema that your function can query as input to customize delivery options. Your function receives only the fields that you request in the input query. To optimize performance, we highly recommend that you request only the fields that your function requires.

    • cart

      Cart!

      non-null

      The cart where the Function is running. A cart contains the merchandise that a customer intends to purchase and information about the customer, such as the customer's email address and phone number.

      • attribute

        Attribute

        The custom attributes associated with a cart to store additional information. Cart attributes allow you to collect specific information from customers on the Cart page, such as order notes, gift wrapping requests, or custom product details. Attributes are stored as key-value pairs.

        • key

          String

          Arguments

          The key of the cart attribute to retrieve. For example, "gift_wrapping".


        • key

          String!

          non-null

          Fields

          The key or name of the attribute. For example, "customer_first_order".

        • value

          String

          The value of the attribute. For example, "true".

      • billing​Address

        Mailing​Address

        The billing address associated with the cart.

        • address1

          String

          The first line of the address. Typically the street address or PO Box number.

        • address2

          String

          The second line of the address. Typically the number of the apartment, suite, or unit.

        • city

          String

          The name of the city, district, village, or town.

        • company

          String

          The name of the customer's company or organization.

        • country​Code

          Country​Code

          The two-letter code for the country of the address. For example, US.

          • AC, AD, AE, AF, AG, AI, AL, AM, AN, AO, AR, AT, AU, AW, AX, AZ, BA, BB, BD, BE, BF, BG, BH, BI, BJ, BL, BM, BN, BO, BQ, BR, BS, BT, BV, BW, BY, BZ, CA, CC, CD, CF, CG, CH, CI, CK, CL, CM, CN, CO, CR, CU, CV, CW, CX, CY, CZ, DE, DJ, DK, DM, DO, DZ, EC, EE, EG, EH, ER, ES, ET, FI, FJ, FK, FO, FR, GA, GB, GD, GE, GF, GG, GH, GI, GL, GM, GN, GP, GQ, GR, GS, GT, GW, GY, HK, HM, HN, HR, HT, HU, ID, IE, IL, IM, IN, IO, IQ, IR, IS, IT, JE, JM, JO, JP, KE, KG, KH, KI, KM, KN, KP, KR, KW, KY, KZ, LA, LB, LC, LI, LK, LR, LS, LT, LU, LV, LY, MA, MC, MD, ME, MF, MG, MK, ML, MM, MN, MO, MQ, MR, MS, MT, MU, MV, MW, MX, MY, MZ, NA, NC, NE, NF, NG, NI, NL, NO, NP, NR, NU, NZ, OM, PA, PE, PF, PG, PH, PK, PL, PM, PN, PS, PT, PY, QA, RE, RO, RS, RU, RW, SA, SB, SC, SD, SE, SG, SH, SI, SJ, SK, SL, SM, SN, SO, SR, SS, ST, SV, SX, SY, SZ, TA, TC, TD, TF, TG, TH, TJ, TK, TL, TM, TN, TO, TR, TT, TV, TW, TZ, UA, UG, UM, US, UY, UZ, VA, VC, VE, VG, VN, VU, WF, WS, XK, YE, YT, ZA, ZM, ZW, ZZ
        • first​Name

          String

          The first name of the customer.

        • last​Name

          String

          The last name of the customer.

        • latitude

          Float

          The approximate latitude of the address.

        • longitude

          Float

          The approximate longitude of the address.

        • name

          String

          The full name of the customer, based on firstName and lastName.

        • phone

          String

          A unique phone number for the customer. Formatted using E.164 standard. For example, +16135551111.

        • province​Code

          String

          The alphanumeric code for the region. For example, ON.

        • zip

          String

          The zip or postal code of the address.

        • market

          Market

          Deprecated

          • handle

            Handle!

            non-null

            A human-readable unique string for the market automatically generated from its title.

          • id

            ID!

            non-null

            A globally-unique identifier.

          • metafield

            Metafield

            A custom field that stores additional information about a Shopify resource, such as products, orders, and many more. Using metafields with Shopify Functions enables you to customize the checkout experience.

            • namespace

              String

              Arguments

              A category that organizes a group of metafields. Namespaces are used to prevent naming conflicts between different apps or different parts of the same app. If omitted, then the app-reserved namespace is used.

            • key

              String!

              required

              The unique identifier for the metafield within its namespace. A metafield is composed of a namespace and a key, in the format namespace.key.


            • json​Value

              JSON!

              non-null

              Fields

              The data that's stored in the metafield, using JSON format.

            • type

              String!

              non-null

              The type of data that the metafield stores in the value field.

            • value

              String!

              non-null

              The data that's stored in the metafield. The data is always stored as a string, regardless of the metafield's type.

          • regions

            [Market​Region!]!

            non-null

            A geographic region which comprises a market.

            • name

              String

              The name of the region in the language of the current localization.

      • buyer​Identity

        Buyer​Identity

        Information about the customer that's interacting with the cart. It includes details such as the customer's email and phone number, and the total amount of money the customer has spent in the store. This information helps personalize the checkout experience and ensures that accurate pricing and delivery options are displayed to customers.

        • customer

          Customer

          The customer that's interacting with the cart.

          • amount​Spent

            Money​V2!

            non-null

            The total amount that the customer has spent on orders. The amount is converted from the shop's currency to the currency of the cart using a market rate.

            • amount

              Decimal!

              non-null

              A monetary value in decimal format, allowing for precise representation of cents or fractional currency. For example, 12.99.

            • currency​Code

              Currency​Code!

              non-null

              The three-letter currency code that represents a world currency used in a store. Currency codes include standard standard ISO 4217 codes, legacy codes, and non-standard codes. For example, USD.

              • AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BTN, BWP, BYN, BZD, CAD, CDF, CHF, CLP, CNY, COP, CRC, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ERN, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, IQD, IRR, ISK, JEP, JMD, JOD, JPY, KES, KGS, KHR, KID, KMF, KRW, KWD, KYD, KZT, LAK, LBP, LKR, LRD, LSL, LTL, LVL, LYD, MAD, MDL, MGA, MKD, MMK, MNT, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PAB, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SDG, SEK, SGD, SHP, SLL, SOS, SRD, SSP, STN, SYP, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UAH, UGX, USD, USDC, UYU, UZS, VED, VES, VND, VUV, WST, XAF, XCD, XOF, XPF, XXX, YER, ZAR, ZMW, BYR, STD, VEF
          • display​Name

            String!

            non-null

            The full name of the customer, based on the values for firstName and lastName. If firstName and lastName aren't specified, then the value is the customer's email address. If the email address isn't specified, then the value is the customer's phone number.

          • email

            String

            The customer's email address.

          • first​Name

            String

            The customer's first name.

          • has​Any​Tag

            Boolean!

            non-null

            Whether the customer is associated with any of the specified tags. The customer must have at least one tag from the list to return true.

            • tags

              [String!]!

              requiredDefault:[]

              Arguments

              A comma-separated list of searchable keywords that are associated with the customer. For example, "VIP, Gold" returns customers with either the VIP or Gold tag.


          • has​Tags

            [Has​Tag​Response!]!

            non-null

            Whether the customer is associated with the specified tags.

            • tags

              [String!]!

              requiredDefault:[]

              Arguments

              A comma-separated list of searchable keywords that are associated with the customer. For example, "VIP, Gold" returns customers with both the VIP and Gold tags.


            • has​Tag

              Boolean!

              non-null

              Fields

              Whether the Shopify resource has the tag.

            • tag

              String!

              non-null

              A searchable keyword that's associated with a Shopify resource, such as a product or customer. For example, a merchant might apply the sports and summer tags to products that are associated with sportswear for summer.

          • id

            ID!

            non-null

            A globally-unique ID for the customer.

          • last​Name

            String

            The customer's last name.

          • metafield

            Metafield

            A custom field that stores additional information about a Shopify resource, such as products, orders, and many more. Using metafields with Shopify Functions enables you to customize the checkout experience.

          • number​Of​Orders

            Int!

            non-null

            The total number of orders that the customer has made at the store.

        • email

          String

          The email address of the customer that's interacting with the cart.

        • is​Authenticated

          Boolean!

          non-null

          Whether the customer is authenticated through their customer account.

        • phone

          String

          The phone number of the customer that's interacting with the cart.

        • purchasing​Company

          Purchasing​Company

          The company of a B2B customer that's interacting with the cart. Used to manage and track purchases made by businesses rather than individual customers.

          • company

            Company!

            non-null

            The company associated to the order or draft order.

            • created​At

              Date​Time!

              non-null

              The date and time (ISO 8601 format) at which the company was created in Shopify.

            • external​Id

              String

              A unique externally-supplied ID for the company.

            • id

              ID!

              non-null

              The ID of the company.

            • metafield

              Metafield

              A custom field that stores additional information about a Shopify resource, such as products, orders, and many more. Using metafields with Shopify Functions enables you to customize the checkout experience.

            • name

              String!

              non-null

              The name of the company.

            • updated​At

              Date​Time!

              non-null

              The date and time (ISO 8601 format) at which the company was last modified.

          • contact

            Company​Contact

            The company contact associated to the order or draft order.

            • created​At

              Date​Time!

              non-null

              The date and time (ISO 8601 format) at which the company contact was created in Shopify.

            • id

              ID!

              non-null

              The ID of the company.

            • locale

              String

              The company contact's locale (language).

            • title

              String

              The company contact's job title.

            • updated​At

              Date​Time!

              non-null

              The date and time (ISO 8601 format) at which the company contact was last modified.

          • location

            Company​Location!

            non-null

            The company location associated to the order or draft order.

            • created​At

              Date​Time!

              non-null

              The date and time (ISO 8601 format) at which the company location was created in Shopify.

            • external​Id

              String

              A unique externally-supplied ID for the company.

            • id

              ID!

              non-null

              The ID of the company.

            • locale

              String

              The preferred locale of the company location.

            • metafield

              Metafield

              A custom field that stores additional information about a Shopify resource, such as products, orders, and many more. Using metafields with Shopify Functions enables you to customize the checkout experience.

            • name

              String!

              non-null

              The name of the company location.

            • orders​Count

              Int!

              non-null

              The number of orders placed at this company location.

            • total​Spent

              Money​V2!

              non-null

              The total amount spent at this company location.

              • amount

                Decimal!

                non-null

                A monetary value in decimal format, allowing for precise representation of cents or fractional currency. For example, 12.99.

              • currency​Code

                Currency​Code!

                non-null

                The three-letter currency code that represents a world currency used in a store. Currency codes include standard standard ISO 4217 codes, legacy codes, and non-standard codes. For example, USD.

            • updated​At

              Date​Time!

              non-null

              The date and time (ISO 8601 format) at which the company location was last modified.

      • cost

        Cart​Cost!

        non-null

        A breakdown of the costs that the customer will pay at checkout. It includes the total amount, the subtotal before taxes and duties, the tax amount, and duty charges.

        • subtotal​Amount

          Money​V2!

          non-null

          The amount, before taxes and cart-level discounts, for the customer to pay.

          • amount

            Decimal!

            non-null

            A monetary value in decimal format, allowing for precise representation of cents or fractional currency. For example, 12.99.

          • currency​Code

            Currency​Code!

            non-null

            The three-letter currency code that represents a world currency used in a store. Currency codes include standard standard ISO 4217 codes, legacy codes, and non-standard codes. For example, USD.

        • total​Amount

          Money​V2!

          non-null

          The total amount for the customer to pay at checkout.

          • amount

            Decimal!

            non-null

            A monetary value in decimal format, allowing for precise representation of cents or fractional currency. For example, 12.99.

          • currency​Code

            Currency​Code!

            non-null

            The three-letter currency code that represents a world currency used in a store. Currency codes include standard standard ISO 4217 codes, legacy codes, and non-standard codes. For example, USD.

        • total​Duty​Amount

          Money​V2

          The duty charges for a customer to pay at checkout.

          • amount

            Decimal!

            non-null

            A monetary value in decimal format, allowing for precise representation of cents or fractional currency. For example, 12.99.

          • currency​Code

            Currency​Code!

            non-null

            The three-letter currency code that represents a world currency used in a store. Currency codes include standard standard ISO 4217 codes, legacy codes, and non-standard codes. For example, USD.

        • total​Tax​Amount

          Money​V2

          The total tax amount for the customer to pay at checkout.

          • amount

            Decimal!

            non-null

            A monetary value in decimal format, allowing for precise representation of cents or fractional currency. For example, 12.99.

          • currency​Code

            Currency​Code!

            non-null

            The three-letter currency code that represents a world currency used in a store. Currency codes include standard standard ISO 4217 codes, legacy codes, and non-standard codes. For example, USD.

      • deliverable​Lines

        [Deliverable​Cart​Line!]!

        non-null

        The items in a cart that are eligible for fulfillment and can be delivered to the customer.

        • attribute

          Attribute

          The custom attributes associated with a cart to store additional information. Cart attributes allow you to collect specific information from customers on the Cart page, such as order notes, gift wrapping requests, or custom product details. Attributes are stored as key-value pairs.

          Cart line attributes are equivalent to the line_item object in Liquid.

        • id

          ID!

          non-null

          The ID of the cart line.

        • merchandise

          Merchandise!

          non-null

          The item that the customer intends to purchase.

          • Custom​Product

            OBJECT

            A custom product represents a product that doesn't map to Shopify's standard product categories. For example, you can use a custom product to manage gift cards, shipping requirements, localized product information, or weight measurements and conversions.

            • is​Gift​Card

              Boolean!

              non-null

              Whether the merchandise is a gift card.

            • requires​Shipping

              Boolean!

              non-null

              Whether the item needs to be shipped to the customer. For example, a digital gift card doesn't need to be shipped, but a t-shirt does need to be shipped.

            • title

              String!

              non-null

              The localized name for the product that displays to customers. The title is used to construct the product's handle, which is a unique, human-readable string of the product's title. For example, if a product is titled "Black Sunglasses", then the handle is black-sunglasses.

            • weight

              Float

              The product variant's weight, in the system of measurement set in the weightUnit field.

            • weight​Unit

              Weight​Unit!

              non-null

              The unit of measurement for weight.

              • GRAMS, KILOGRAMS, OUNCES, POUNDS
          • Product​Variant

            OBJECT

            A specific version of a product that comes in more than one option, such as size or color. For example, if a merchant sells t-shirts with options for size and color, then a small, blue t-shirt would be one product variant and a large, blue t-shirt would be another.

            • id

              ID!

              non-null

              A globally-unique ID for the product variant.

            • metafield

              Metafield

              A custom field that stores additional information about a Shopify resource, such as products, orders, and many more. Using metafields with Shopify Functions enables you to customize the checkout experience.

            • product

              Product!

              non-null

              The product associated with the product variant. For example, if a merchant sells t-shirts with options for size and color, then a small, blue t-shirt would be one product variant and a large, blue t-shirt would be another. The product associated with the product variant would be the t-shirt itself.

              • handle

                Handle!

                non-null

                A unique, human-readable string of the product's title. A handle can contain letters, hyphens (-), and numbers, but not spaces. The handle is used in the online store URL for the product. For example, if a product is titled "Black Sunglasses", then the handle is black-sunglasses.

              • has​Any​Tag

                Boolean!

                non-null

                Whether the product is associated with any of the specified tags. The product must have at least one tag from the list to return true.

              • has​Tags

                [Has​Tag​Response!]!

                non-null

                Whether the product is associated with the specified tags.

              • id

                ID!

                non-null

                A globally-unique ID for the product.

              • in​Any​Collection

                Boolean!

                non-null

                Whether the product is in any of the specified collections. The product must be in at least one collection from the list to return true.

                A collection is a group of products that can be displayed in online stores and other sales channels in categories, which makes it easy for customers to find them. For example, an athletics store might create different collections for running attire and accessories.

              • in​Collections

                [Collection​Membership!]!

                non-null

                Whether the product is in the specified collections. The product must be in all of the collections in the list to return true.

                A collection is a group of products that can be displayed in online stores and other sales channels in categories, which makes it easy for customers to find them. For example, an athletics store might create different collections for running attire and accessories.

                • ids

                  [ID!]!

                  requiredDefault:[]

                  Arguments

                  A comma-separated list of globally-unique collection IDs that are associated with the product. For example, gid://shopify/Collection/123, gid://shopify/Collection/456.


                • collection​Id

                  ID!

                  non-null

                  Fields

                  A globally-unique ID for the collection.

                • is​Member

                  Boolean!

                  non-null

                  Whether the product is in the specified collection.

              • is​Gift​Card

                Boolean!

                non-null

                Whether the product is a gift card.

              • metafield

                Metafield

                A custom field that stores additional information about a Shopify resource, such as products, orders, and many more. Using metafields with Shopify Functions enables you to customize the checkout experience.

              • product​Type

                String

                A custom category for a product. Product types allow merchants to define categories other than the ones available in Shopify's standard product categories.

              • title

                String!

                non-null

                The localized name for the product that displays to customers. The title is used to construct the product's handle, which is a unique, human-readable string of the product's title. For example, if a product is titled "Black Sunglasses", then the handle is black-sunglasses.

              • vendor

                String

                The name of the product's vendor.

            • requires​Shipping

              Boolean!

              non-null

              Whether the item needs to be shipped to the customer. For example, a digital gift card doesn't need to be shipped, but a t-shirt does need to be shipped.

            • sku

              String

              A case-sensitive identifier for the product variant in the merchant's store. For example, "BBC-1". A product variant must have a SKU to be connected to a fulfillment service.

            • title

              String

              The localized name for the product variant that displays to customers.

            • weight

              Float

              The product variant's weight, in the system of measurement set in the weightUnit field.

            • weight​Unit

              Weight​Unit!

              non-null

              The unit of measurement for weight.

        • quantity

          Int!

          non-null

          The quantity of the item that the customer intends to purchase.

      • delivery​Groups

        [Cart​Delivery​Group!]!

        non-null

        A collection of items that are grouped by shared delivery characteristics. Delivery groups streamline fulfillment by organizing items that can be shipped together, based on the customer's shipping address. For example, if a customer orders a t-shirt and a pair of shoes that can be shipped together, then the items are included in the same delivery group.

        In the Order Discount and Product Discount legacy APIs, the cart.deliveryGroups input is always an empty array. This means you can't access delivery groups when creating Order Discount or Product Discount Functions. If you need to apply discounts to shipping costs, then use the Discount Function API instead.

        • cart​Lines

          [Cart​Line!]!

          non-null

          Information about items in a cart that a customer intends to purchase. A cart line is an entry in the customer's cart that represents a single unit of a product variant. For example, if a customer adds two different sizes of the same t-shirt to their cart, then each size is represented as a separate cart line.

          • attribute

            Attribute

            The custom attributes associated with a cart to store additional information. Cart attributes allow you to collect specific information from customers on the Cart page, such as order notes, gift wrapping requests, or custom product details. Attributes are stored as key-value pairs.

            Cart line attributes are equivalent to the line_item object in Liquid.

          • cost

            Cart​Line​Cost!

            non-null

            The cost of an item in a cart that the customer intends to purchase. Cart lines are entries in the customer's cart that represent a single unit of a product variant. For example, if a customer adds two different sizes of the same t-shirt to their cart, then each size is represented as a separate cart line.

          • discount​Allocations

            [Discount​Allocation!]!

            non-null

            The discounts that have been applied to the cart line.

            • discount​Application

              Discount​Application!

              non-null

              The discount that was applied.

              • allocation​Method

                Discount​Application​Allocation​Method!

                non-null

                The method by which the discount's value is allocated to its entitled items.

                • ACROSS, EACH
              • metafield

                Metafield

                A custom field that stores additional information about a Shopify resource, such as products, orders, and many more. Using metafields with Shopify Functions enables you to customize the checkout experience.

              • target​Selection

                Discount​Application​Target​Selection!

                non-null

                The lines on the cart targeted by the discount.

                • ALL, ENTITLED, EXPLICIT
              • target​Type

                Discount​Application​Target!

                non-null

                The type of line (i.e. line item or shipping line) on a cart that the discount is applicable towards.

                • LINE_ITEM, SHIPPING_LINE
              • total​Allocated​Amount

                Money​V2!

                non-null

                The total allocated amount of the discount across all items.

                • amount

                  Decimal!

                  non-null

                  A monetary value in decimal format, allowing for precise representation of cents or fractional currency. For example, 12.99.

                • currency​Code

                  Currency​Code!

                  non-null

                  The three-letter currency code that represents a world currency used in a store. Currency codes include standard standard ISO 4217 codes, legacy codes, and non-standard codes. For example, USD.

              • value

                Pricing​Value!

                non-null

                The value of the discount.

                • Money​V2

                  OBJECT

                  A precise monetary value and its associated currency. Combines a decimal amount with a three-letter currency code to express prices, costs, and other financial values throughout the API. For example, 12.99 USD.

                  • amount

                    Decimal!

                    non-null

                    A monetary value in decimal format, allowing for precise representation of cents or fractional currency. For example, 12.99.

                  • currency​Code

                    Currency​Code!

                    non-null

                    The three-letter currency code that represents a world currency used in a store. Currency codes include standard standard ISO 4217 codes, legacy codes, and non-standard codes. For example, USD.

                • Pricing​Percentage​Value

                  OBJECT

                  The percentage value of a discount.

                  • value

                    Decimal!

                    non-null

                    The percentage value of the discount.

            • discounted​Amount

              Money​V2!

              non-null

              The amount that was discounted.

              • amount

                Decimal!

                non-null

                A monetary value in decimal format, allowing for precise representation of cents or fractional currency. For example, 12.99.

              • currency​Code

                Currency​Code!

                non-null

                The three-letter currency code that represents a world currency used in a store. Currency codes include standard standard ISO 4217 codes, legacy codes, and non-standard codes. For example, USD.

          • id

            ID!

            non-null

            The ID of the cart line.

          • merchandise

            Merchandise!

            non-null

            The item that the customer intends to purchase.

          • parent​Relationship

            Cart​Line​Parent​Relationship

            The nested relationship between this line and its parent line, if any.

            • parent

              Cart​Line!

              non-null

              The parent line in the relationship.

          • quantity

            Int!

            non-null

            The quantity of the item that the customer intends to purchase.

          • selling​Plan​Allocation

            Selling​Plan​Allocation

            The selling plan associated with the cart line, including information about how a product variant can be sold and purchased.

            • price​Adjustments

              [Selling​Plan​Allocation​Price​Adjustment!]!

              non-null

              A list of price adjustments, with a maximum of two. When there are two, the first price adjustment goes into effect at the time of purchase, while the second one starts after a certain number of orders. A price adjustment represents how a selling plan affects pricing when a variant is purchased with a selling plan. Prices display in the customer's currency if the shop is configured for it.

              • per​Delivery​Price

                Money​V2!

                non-null

                The effective price for a single delivery. For example, for a prepaid subscription plan that includes 6 deliveries at the price of $48.00, the per delivery price is $8.00.

                • amount

                  Decimal!

                  non-null

                  A monetary value in decimal format, allowing for precise representation of cents or fractional currency. For example, 12.99.

                • currency​Code

                  Currency​Code!

                  non-null

                  The three-letter currency code that represents a world currency used in a store. Currency codes include standard standard ISO 4217 codes, legacy codes, and non-standard codes. For example, USD.

              • price

                Money​V2!

                non-null

                The price of the variant when it's purchased with a selling plan For example, for a prepaid subscription plan that includes 6 deliveries of $10.00 granola, where the customer gets 20% off, the price is 6 x $10.00 x 0.80 = $48.00.

                • amount

                  Decimal!

                  non-null

                  A monetary value in decimal format, allowing for precise representation of cents or fractional currency. For example, 12.99.

                • currency​Code

                  Currency​Code!

                  non-null

                  The three-letter currency code that represents a world currency used in a store. Currency codes include standard standard ISO 4217 codes, legacy codes, and non-standard codes. For example, USD.

            • selling​Plan

              Selling​Plan!

              non-null

              A representation of how products and variants can be sold and purchased. For example, an individual selling plan could be '6 weeks of prepaid granola, delivered weekly'.

              • description

                String

                The description of the selling plan.

              • id

                ID!

                non-null

                A globally-unique identifier.

              • metafield

                Metafield

                A custom field that stores additional information about a Shopify resource, such as products, orders, and many more. Using metafields with Shopify Functions enables you to customize the checkout experience.

              • name

                String!

                non-null

                The name of the selling plan. For example, '6 weeks of prepaid granola, delivered weekly'.

              • recurring​Deliveries

                Boolean!

                non-null

                Whether purchasing the selling plan will result in multiple deliveries.

        • delivery​Address

          Mailing​Address

          The shipping or destination address associated with the delivery group.

          • address1

            String

            The first line of the address. Typically the street address or PO Box number.

          • address2

            String

            The second line of the address. Typically the number of the apartment, suite, or unit.

          • city

            String

            The name of the city, district, village, or town.

          • company

            String

            The name of the customer's company or organization.

          • country​Code

            Country​Code

            The two-letter code for the country of the address. For example, US.

          • first​Name

            String

            The first name of the customer.

          • last​Name

            String

            The last name of the customer.

          • latitude

            Float

            The approximate latitude of the address.

          • longitude

            Float

            The approximate longitude of the address.

          • name

            String

            The full name of the customer, based on firstName and lastName.

          • phone

            String

            A unique phone number for the customer. Formatted using E.164 standard. For example, +16135551111.

          • province​Code

            String

            The alphanumeric code for the region. For example, ON.

          • zip

            String

            The zip or postal code of the address.

          • market

            Market

            Deprecated

        • delivery​Options

          [Cart​Delivery​Option!]!

          non-null

          The delivery options available for the delivery group. Delivery options are the different ways that customers can choose to have their orders shipped. Examples include express shipping or standard shipping.

          • code

            String

            A unique identifier that represents the delivery option offered to customers. For example, Canada Post Expedited.

          • cost

            Money​V2!

            non-null

            The amount that the customer pays if they select the delivery option.

          • delivery​Method​Type

            Delivery​Method!

            non-null

            The delivery method associated with the delivery option. A delivery method is a way that merchants can fulfill orders from their online stores. Delivery methods include shipping to an address, local pickup, and shipping to a pickup point, all of which are natively supported by Shopify checkout.

            • LOCAL, NONE, PICK_UP, PICKUP_POINT, RETAIL, SHIPPING
          • description

            String

            A single-line description of the delivery option, with HTML tags removed.

          • handle

            Handle!

            non-null

            A unique, human-readable identifier of the delivery option's title. A handle can contain letters, hyphens (-), and numbers, but not spaces. For example, standard-shipping.

          • title

            String

            The name of the delivery option that displays to customers. The title is used to construct the delivery option's handle. For example, if a delivery option is titled "Standard Shipping", then the handle is standard-shipping.

        • discount​Allocations

          [Discount​Allocation!]!

          non-null

          The discounts that have been applied to the delivery group.

        • group​Type

          Cart​Delivery​Group​Type!

          non-null

          The type of merchandise in the delivery group.

          • ONE_TIME_PURCHASE, SUBSCRIPTION
        • id

          ID!

          non-null

          A globally-unique ID for the delivery group.

        • selected​Delivery​Option

          Cart​Delivery​Option

          Information about the delivery option that the customer has selected.

          • code

            String

            A unique identifier that represents the delivery option offered to customers. For example, Canada Post Expedited.

          • cost

            Money​V2!

            non-null

            The amount that the customer pays if they select the delivery option.

          • delivery​Method​Type

            Delivery​Method!

            non-null

            The delivery method associated with the delivery option. A delivery method is a way that merchants can fulfill orders from their online stores. Delivery methods include shipping to an address, local pickup, and shipping to a pickup point, all of which are natively supported by Shopify checkout.

          • description

            String

            A single-line description of the delivery option, with HTML tags removed.

          • handle

            Handle!

            non-null

            A unique, human-readable identifier of the delivery option's title. A handle can contain letters, hyphens (-), and numbers, but not spaces. For example, standard-shipping.

          • title

            String

            The name of the delivery option that displays to customers. The title is used to construct the delivery option's handle. For example, if a delivery option is titled "Standard Shipping", then the handle is standard-shipping.

      • discount​Applications

        [Discount​Application!]!

        non-null

        The discounts that have been applied to the cart.

        • allocation​Method

          Discount​Application​Allocation​Method!

          non-null

          The method by which the discount's value is allocated to its entitled items.

        • metafield

          Metafield

          A custom field that stores additional information about a Shopify resource, such as products, orders, and many more. Using metafields with Shopify Functions enables you to customize the checkout experience.

        • target​Selection

          Discount​Application​Target​Selection!

          non-null

          The lines on the cart targeted by the discount.

        • target​Type

          Discount​Application​Target!

          non-null

          The type of line (i.e. line item or shipping line) on a cart that the discount is applicable towards.

        • total​Allocated​Amount

          Money​V2!

          non-null

          The total allocated amount of the discount across all items.

        • value

          Pricing​Value!

          non-null

          The value of the discount.

      • lines

        [Cart​Line!]!

        non-null

        The items in a cart that the customer intends to purchase. A cart line is an entry in the customer's cart that represents a single unit of a product variant. For example, if a customer adds two different sizes of the same t-shirt to their cart, then each size is represented as a separate cart line.

        • attribute

          Attribute

          The custom attributes associated with a cart to store additional information. Cart attributes allow you to collect specific information from customers on the Cart page, such as order notes, gift wrapping requests, or custom product details. Attributes are stored as key-value pairs.

          Cart line attributes are equivalent to the line_item object in Liquid.

        • cost

          Cart​Line​Cost!

          non-null

          The cost of an item in a cart that the customer intends to purchase. Cart lines are entries in the customer's cart that represent a single unit of a product variant. For example, if a customer adds two different sizes of the same t-shirt to their cart, then each size is represented as a separate cart line.

        • discount​Allocations

          [Discount​Allocation!]!

          non-null

          The discounts that have been applied to the cart line.

        • id

          ID!

          non-null

          The ID of the cart line.

        • merchandise

          Merchandise!

          non-null

          The item that the customer intends to purchase.

        • parent​Relationship

          Cart​Line​Parent​Relationship

          The nested relationship between this line and its parent line, if any.

        • quantity

          Int!

          non-null

          The quantity of the item that the customer intends to purchase.

        • selling​Plan​Allocation

          Selling​Plan​Allocation

          The selling plan associated with the cart line, including information about how a product variant can be sold and purchased.

      • localized​Fields

        [Localized​Field!]!

        non-null

        The additional fields on the Cart page that are required for international orders in specific countries, such as customs information or tax identification numbers.

        • keys

          [Localized​Field​Key!]!

          requiredDefault:[]

          Arguments

          The keys of the localized fields to retrieve.

          • SHIPPING_CREDENTIAL_BR, SHIPPING_CREDENTIAL_CL, SHIPPING_CREDENTIAL_CN, SHIPPING_CREDENTIAL_CO, SHIPPING_CREDENTIAL_CR, SHIPPING_CREDENTIAL_EC, SHIPPING_CREDENTIAL_ES, SHIPPING_CREDENTIAL_GT, SHIPPING_CREDENTIAL_ID, SHIPPING_CREDENTIAL_KR, SHIPPING_CREDENTIAL_MX, SHIPPING_CREDENTIAL_MY, SHIPPING_CREDENTIAL_PE, SHIPPING_CREDENTIAL_PT, SHIPPING_CREDENTIAL_PY, SHIPPING_CREDENTIAL_TR, SHIPPING_CREDENTIAL_TW, SHIPPING_CREDENTIAL_TYPE_CO, TAX_CREDENTIAL_BR, TAX_CREDENTIAL_CL, TAX_CREDENTIAL_CO, TAX_CREDENTIAL_CR, TAX_CREDENTIAL_EC, TAX_CREDENTIAL_ES, TAX_CREDENTIAL_GT, TAX_CREDENTIAL_ID, TAX_CREDENTIAL_IT, TAX_CREDENTIAL_MX, TAX_CREDENTIAL_MY, TAX_CREDENTIAL_PE, TAX_CREDENTIAL_PT, TAX_CREDENTIAL_PY, TAX_CREDENTIAL_TR, TAX_CREDENTIAL_TYPE_CO, TAX_CREDENTIAL_TYPE_MX, TAX_CREDENTIAL_USE_MX, TAX_EMAIL_IT

        • key

          Localized​Field​Key!

          non-null

          Fields

          The key of the localized field.

          • SHIPPING_CREDENTIAL_BR, SHIPPING_CREDENTIAL_CL, SHIPPING_CREDENTIAL_CN, SHIPPING_CREDENTIAL_CO, SHIPPING_CREDENTIAL_CR, SHIPPING_CREDENTIAL_EC, SHIPPING_CREDENTIAL_ES, SHIPPING_CREDENTIAL_GT, SHIPPING_CREDENTIAL_ID, SHIPPING_CREDENTIAL_KR, SHIPPING_CREDENTIAL_MX, SHIPPING_CREDENTIAL_MY, SHIPPING_CREDENTIAL_PE, SHIPPING_CREDENTIAL_PT, SHIPPING_CREDENTIAL_PY, SHIPPING_CREDENTIAL_TR, SHIPPING_CREDENTIAL_TW, SHIPPING_CREDENTIAL_TYPE_CO, TAX_CREDENTIAL_BR, TAX_CREDENTIAL_CL, TAX_CREDENTIAL_CO, TAX_CREDENTIAL_CR, TAX_CREDENTIAL_EC, TAX_CREDENTIAL_ES, TAX_CREDENTIAL_GT, TAX_CREDENTIAL_ID, TAX_CREDENTIAL_IT, TAX_CREDENTIAL_MX, TAX_CREDENTIAL_MY, TAX_CREDENTIAL_PE, TAX_CREDENTIAL_PT, TAX_CREDENTIAL_PY, TAX_CREDENTIAL_TR, TAX_CREDENTIAL_TYPE_CO, TAX_CREDENTIAL_TYPE_MX, TAX_CREDENTIAL_USE_MX, TAX_EMAIL_IT
        • title

          String!

          non-null

          The title of the localized field.

        • value

          String

          The value of the localized field.

      • metafield

        Metafield

        A custom field that stores additional information about a Shopify resource, such as products, orders, and many more. Using metafields with Shopify Functions enables you to customize the checkout experience.

      • po​Number

        String

        A purchase order number associated with the cart, often used for B2B transactions to reference the buyer's internal purchase order.

      • retail​Location

        Location

        The physical location where a retail order is created or completed.

        • address

          Location​Address!

          non-null

          The address of this location.

          • address1

            String

            The first line of the address for the location.

          • address2

            String

            The second line of the address for the location.

          • city

            String

            The city of the location.

          • country

            String

            The country of the location.

          • country​Code

            String

            The country code of the location.

          • formatted

            [String!]!

            non-null

            A formatted version of the address for the location.

          • latitude

            Float

            The approximate latitude coordinates of the location.

          • longitude

            Float

            The approximate longitude coordinates of the location.

          • phone

            String

            The phone number of the location.

          • province

            String

            The province of the location.

          • province​Code

            String

            The code for the province, state, or district of the address of the location.

          • zip

            String

            The ZIP code of the location.

        • handle

          Handle!

          non-null

          The location handle.

        • id

          ID!

          non-null

          The location id.

        • metafield

          Metafield

          A custom field that stores additional information about a Shopify resource, such as products, orders, and many more. Using metafields with Shopify Functions enables you to customize the checkout experience.

        • name

          String!

          non-null

          The name of the location.

    • delivery​Customization

      Delivery​Customization!

      non-null

      The backend logic that the Function is running to define how delivery options are sorted, hidden, or renamed. It includes the metafields that are associated with the customization.

    • localization

      Localization!

      non-null

      The regional and language settings that determine how the Function handles currency, numbers, dates, and other locale-specific values during discount calculations. These settings are based on the store's configured localization practices.

      • country

        Country!

        non-null

        The country for which the store is customized, reflecting local preferences and regulations. Localization might influence the language, currency, and product offerings available in a store to enhance the shopping experience for customers in that region.

        • iso​Code

          Country​Code!

          non-null

          The ISO code of the country.

          • AC, AD, AE, AF, AG, AI, AL, AM, AN, AO, AR, AT, AU, AW, AX, AZ, BA, BB, BD, BE, BF, BG, BH, BI, BJ, BL, BM, BN, BO, BQ, BR, BS, BT, BV, BW, BY, BZ, CA, CC, CD, CF, CG, CH, CI, CK, CL, CM, CN, CO, CR, CU, CV, CW, CX, CY, CZ, DE, DJ, DK, DM, DO, DZ, EC, EE, EG, EH, ER, ES, ET, FI, FJ, FK, FO, FR, GA, GB, GD, GE, GF, GG, GH, GI, GL, GM, GN, GP, GQ, GR, GS, GT, GW, GY, HK, HM, HN, HR, HT, HU, ID, IE, IL, IM, IN, IO, IQ, IR, IS, IT, JE, JM, JO, JP, KE, KG, KH, KI, KM, KN, KP, KR, KW, KY, KZ, LA, LB, LC, LI, LK, LR, LS, LT, LU, LV, LY, MA, MC, MD, ME, MF, MG, MK, ML, MM, MN, MO, MQ, MR, MS, MT, MU, MV, MW, MX, MY, MZ, NA, NC, NE, NF, NG, NI, NL, NO, NP, NR, NU, NZ, OM, PA, PE, PF, PG, PH, PK, PL, PM, PN, PS, PT, PY, QA, RE, RO, RS, RU, RW, SA, SB, SC, SD, SE, SG, SH, SI, SJ, SK, SL, SM, SN, SO, SR, SS, ST, SV, SX, SY, SZ, TA, TC, TD, TF, TG, TH, TJ, TK, TL, TM, TN, TO, TR, TT, TV, TW, TZ, UA, UG, UM, US, UY, UZ, VA, VC, VE, VG, VN, VU, WF, WS, XK, YE, YT, ZA, ZM, ZW, ZZ
      • language

        Language!

        non-null

        The language for which the store is customized, ensuring content is tailored to local customers. This includes product descriptions and customer communications that resonate with the target audience.

        • iso​Code

          Language​Code!

          non-null

          The ISO code.

      • market

        Market!

        non-nullDeprecated

    • presentment​Currency​Rate

      Decimal!

      non-null

      The exchange rate used to convert discounts between the shop's default currency and the currency that displays to the customer during checkout. For example, if a store operates in USD but a customer is viewing discounts in EUR, then the presentment currency rate handles this conversion for accurate pricing.

    • shop

      Shop!

      non-null

      Information about the shop where the Function is running, including the shop's timezone setting and associated metafields.

      • local​Time

        Local​Time!

        non-null

        The current time based on the store's timezone setting.

        • date

          Date!

          non-null

          The current date relative to the parent object.

        • date​Time​After

          Boolean!

          non-null

          Returns true if the current date and time is at or past the given date and time, and false otherwise.

        • date​Time​Before

          Boolean!

          non-null

          Returns true if the current date and time is before the given date and time, and false otherwise.

        • date​Time​Between

          Boolean!

          non-null

          Returns true if the current date and time is between the two given date and times, and false otherwise.

        • time​After

          Boolean!

          non-null

          Returns true if the current time is at or past the given time, and false otherwise.

        • time​Before

          Boolean!

          non-null

          Returns true if the current time is at or past the given time, and false otherwise.

        • time​Between

          Boolean!

          non-null

          Returns true if the current time is between the two given times, and false otherwise.

      • metafield

        Metafield

        A custom field that stores additional information about a Shopify resource, such as products, orders, and many more. Using metafields with Shopify Functions enables you to customize the checkout experience.

      • metaobject

        Metaobject

        Fetch a specific Metaobject by one of its unique identifiers. Only app-owned metaobjects with the $app reserved prefix are accessible to functions.

        • handle

          Metaobject​Handle​Input

          Arguments

          The handle and type of the metaobject.

          • handle

            String!

            non-null

            The handle of the metaobject to retrieve.

          • type

            String!

            non-null

            The type of the metaobject. Must match an existing metaobject definition type.

        • id

          ID

          The ID of the metaobject.


        • field

          Metaobject​Field

          Fields

          The field for an object key, or null if the key has no field definition.

          • key

            String!

            required

            Arguments

            The metaobject key to access.


          • json​Value

            JSON

            Fields

            The assigned field value in JSON format.

          • key

            String!

            non-null

            The object key of this field.

          • type

            String!

            non-null

            The type of the field.

          • value

            String

            The assigned field value, always stored as a string regardless of the field type.

        • handle

          String!

          non-null

          The unique handle of the metaobject, useful as a custom ID.

        • type

          String!

          non-null

          The type of the metaobject.

Run function

The logic that processes the input data to generate a standardized list of operations that generate delivery customizations.

Each operation specifies a delivery customization. Shopify processes your response to modify delivery options during checkout, including data such as location details, the company associated with the order, and products.

This return must follow the schema defined in the CartDeliveryOptionsTransformRunResult object.

  • Cart​Delivery​Options​Transform​Run​Result

    OBJECT

    The CartDeliveryOptionsTransformRunResult object is the output of the function run target. The object contains the operations to apply to delivery options in checkout.

    • operations

      [Operation!]!

      non-null

      The ordered list of operations to apply to the list of delivery options.

      • delivery​Option​Hide

        Delivery​Option​Hide​Operation

        An operation that hides a delivery option from a list that's offered to customers at checkout.

        • delivery​Option​Handle

          Handle!

          non-null

          The handle of the delivery option to hide.

      • delivery​Option​Move

        Delivery​Option​Move​Operation

        An operation that sorts a list of delivery options that are offered to customers at checkout.

        If you reorder shipping delivery options, then you are prohibited. from automatically selecting higher-priced delivery alternatives by default. The cheapest shipping delivery option must always be the first option selected.

        • delivery​Option​Handle

          Handle!

          non-null

          The handle of the delivery option to move.

        • index

          Int!

          non-null

          The target index within the delivery group to move the delivery option to.

      • delivery​Option​Rename

        Delivery​Option​Rename​Operation

        An operation that renames a delivery option that's offered to customers at checkout.

        The carrier name is automatically prepended to the delivery option title at checkout when using the DeliveryOptionRenameOperation object, and can't be altered or omitted through the API. For example, if the carrier name is UPS and the option is Standard, then you could change UPS Standard to UPS Standard Shipping, but you couldn't change UPS Standard to Standard Shipping.

        • delivery​Option​Handle

          Handle!

          non-null

          The handle of the delivery option to rename.

        • title

          String!

          non-null

          The new name for the delivery option.

Examples

  • Hide free delivery for perishable items

    This function hides the free delivery option, if the product has a perishable tag, and the delivery address country matches one of the configured countries that is stored in a JSON metafield. Delivery options can also be known as shipping options. The function demonstrates how to: * Read a JSON configuration metafield * Check the delivery address country * Check the product tag * Hide an operation if the conditions are met

    cart.delivery-options.transform.run

    Input Query (Rust)
    query Input {
      deliveryCustomization {
        metafield(
          namespace: "$app:delivery-customization"
          key: "function-configuration"
        ) {
          jsonValue
        }
      }
      cart {
        lines {
          merchandise {
            __typename
            ... on ProductVariant {
              product {
                hasTags(tags: ["perishable"]) {
                  hasTag
                  tag
                }
              }
            }
          }
        }
        deliveryGroups {
          deliveryAddress {
            countryCode
          }
          deliveryOptions {
            title
            cost {
              amount
            }
            handle
          }
        }
      }
    }
    
    Input Query (JavaScript)
    query RunInput {
      deliveryCustomization {
        metafield(
          namespace: "$app:delivery-customization"
          key: "function-configuration"
        ) {
          value
        }
      }
      cart {
        lines {
          merchandise {
            ... on ProductVariant {
              product {
                hasTags(tags: ["perishable"]) {
                  hasTag
                  tag
                }
              }
            }
          }
        }
        deliveryGroups {
          deliveryAddress {
            countryCode
          }
          deliveryOptions {
            title # This is an OPTIONAL field in the input data. It doesn't have a ! at the end in the graphql schema
            cost {
              amount # This is a decimal field in the input data
            }
            handle
          }
        }
      }
    }
    
    Input Object (Rust)
    {
        "deliveryCustomization": {
            "metafield": {
                "jsonValue": {
                  "countryCode": ["CA", "NZ"]
                }
            }
        },
        "cart": {
            "lines": [
                {
                    "merchandise": {
                        "__typename": "ProductVariant",
                        "product": {
                            "hasTags": [
                                {
                                    "hasTag": true,
                                    "tag": "perishable"
                                }
                            ]
                        }
                    }
                }
            ],
            "deliveryGroups": [
                {
                    "deliveryAddress": {
                        "countryCode": "CA"
                    },
                    "deliveryOptions": [
                        {
                            "title": "Standard",
                            "cost": {
                                "amount": "0.0"
                            },
                            "handle": "dc4b9f18d30098469af5fabec87f3434-7bf1540a5810819fcc43fd9808d43db9"
                        },
                        {
                            "title": "Supper express rate",
                            "cost": {
                                "amount": "1.0"
                            },
                            "handle": "dc4b9f18d30098469af5fabec87f3434-b514e01af8655a9229f7a04405396118"
                        },
                        {
                            "title": "Medium Rate",
                            "cost": {
                                "amount": "15.0"
                            },
                            "handle": "dc4b9f18d30098469af5fabec87f3434-fbcaff8dd39a68820109eb990460be0a"
                        },
                        {
                            "title": "Express",
                            "cost": {
                                "amount": "21.9"
                            },
                            "handle": "dc4b9f18d30098469af5fabec87f3434-3da105a249c8aa8bffc74a78b7c66138"
                        }
                    ]
                }
            ]
        }
    }
    
    Input Object (JavaScript)
    {
        "deliveryCustomization": {
          "metafield": {
            "value": "{\"countryCode\":[\"CA\",\"NZ\"]}"
          }
        },
        "cart": {
          "lines": [
            {
              "merchandise": {
                "product": {
                  "hasTags": [
                    {
                      "hasTag": true,
                      "tag": "perishable"
                    }
                  ]
                }
              }
            }
          ],
          "deliveryGroups": [
            {
              "deliveryAddress": {
                "countryCode": "CA"
              },
              "deliveryOptions": [
                {
                  "title": "Standard",
                  "cost": {
                    "amount": "0.0"
                  },
                  "handle": "dc4b9f18d30098469af5fabec87f3434-7bf1540a5810819fcc43fd9808d43db9"
                },
                {
                  "title": "Supper express rate",
                  "cost": {
                    "amount": "1.0"
                  },
                  "handle": "dc4b9f18d30098469af5fabec87f3434-b514e01af8655a9229f7a04405396118"
                },
                {
                  "title": "Medium Rate",
                  "cost": {
                    "amount": "15.0"
                  },
                  "handle": "dc4b9f18d30098469af5fabec87f3434-fbcaff8dd39a68820109eb990460be0a"
                },
                {
                  "title": "Express",
                  "cost": {
                    "amount": "21.9"
                  },
                  "handle": "dc4b9f18d30098469af5fabec87f3434-3da105a249c8aa8bffc74a78b7c66138"
                }
              ]
            }
          ]
        }
      }
    
    Function Code (Rust)
    use crate::schema;
    use shopify_function::prelude::*;
    use shopify_function::Result;
    
    #[derive(Deserialize, Default, PartialEq)]
    #[shopify_function(rename_all = "camelCase")]
    pub struct Configuration {
        country_code: Option<Vec<String>>,
    }
    
    #[shopify_function]
    fn cart_delivery_options_transform_run(
        input: schema::cart_delivery_options_transform_run::Input,
    ) -> Result<schema::CartDeliveryOptionsTransformRunResult> {
        let no_changes = schema::CartDeliveryOptionsTransformRunResult { operations: vec![] };
    
        // Parse configuration from metafield
        let config: &Configuration = match input.delivery_customization().metafield() {
            Some(metafield) => &metafield.json_value(),
            None => return Ok(no_changes),
        };
    
        // Extract configured countries from configuration
        let configured_countries = match config.country_code.as_ref() {
            Some(countries) if !countries.is_empty() => countries,
            _ => return Ok(no_changes),
        };
    
        // Check delivery address country code
        let cart = &input.cart();
    
        let delivery_groups = &cart.delivery_groups();
        if delivery_groups.is_empty() {
            return Ok(no_changes);
        }
    
        let country_code = match &delivery_groups[0].delivery_address() {
            Some(address) => &address.country_code(),
            None => return Ok(no_changes),
        };
    
        // Check if the country code matches any configured country
        let found = if let Some(code) = country_code {
            configured_countries.iter().any(|c| c == *code)
        } else {
            false
        };
    
        if !found {
            return Ok(no_changes);
        }
    
        // Check if any product has the perishable tag
        let cart_lines = &cart.lines();
    
        let has_perishable_item = cart_lines.iter().any(|line| {
            // Check if merchandise is a ProductVariant
            match &line.merchandise() {
                schema::cart_delivery_options_transform_run::input::cart::lines::Merchandise::ProductVariant(variant) => {
                    let product = &variant.product();
                    product.has_tags().iter().any(|tag_response| {
                        *tag_response.has_tag() && tag_response.tag() == "perishable"
                    })
                }
                _ => false,
            }
        });
    
        if !has_perishable_item {
            return Ok(no_changes);
        }
    
        // Find the free delivery option
        let delivery_options = &delivery_groups[0].delivery_options();
        let free_delivery_option = delivery_options.iter().find(|option| {
            let cost = &option.cost();
            let amount_str = cost.amount().to_string();
            if let Ok(amount) = amount_str.parse::<f64>() {
                return amount == 0.0;
            }
            false
        });
    
        let free_delivery_option = match free_delivery_option {
            Some(option) => option,
            None => return Ok(no_changes),
        };
    
        // Hide the free delivery option
        let hide_operation = schema::DeliveryOptionHideOperation {
            delivery_option_handle: free_delivery_option.handle().clone(),
        };
    
        // Create the operations vector
        let mut operations = Vec::new();
        operations.push(schema::Operation::DeliveryOptionHide(hide_operation));
    
        Ok(schema::CartDeliveryOptionsTransformRunResult { operations })
    }
    
    Performance Cost (Rust)

    62308 instructions

    Function Code (JavaScript)
    // @ts-check
    
    /**
     * @typedef {import("../generated/api").RunInput} RunInput
     * @typedef {import("../generated/api").CartDeliveryOptionsTransformRunResult} CartDeliveryOptionsTransformRunResult
     */
    
    /**
     * @type {CartDeliveryOptionsTransformRunResult}
     */
    const NO_CHANGES = {
      operations: [],
    };
    
    /**
     * @param {RunInput} input
     * @returns {CartDeliveryOptionsTransformRunResult}
     */
    export function cartDeliveryOptionsTransformRun(input) {
      // Parse configuration from metafield
      const configuration = JSON.parse(
        input?.deliveryCustomization?.metafield?.value ?? "{}"
      );
    
      // Extract configured countries from configuration
      const configuredCountries = configuration.countryCode || [];
      if (!configuredCountries.length) return NO_CHANGES;
    
      // Check delivery address country code
      const deliveryGroups = input.cart?.deliveryGroups || [];
      if (!deliveryGroups.length) return NO_CHANGES;
    
      const countryCode = deliveryGroups[0]?.deliveryAddress?.countryCode;
      if (!configuredCountries.includes(countryCode)) return NO_CHANGES;
    
      // Check if any product has the perishable tag
      const cartLines = input.cart?.lines || [];
      const hasPerishableItem = cartLines.some(line => {
        // More flexible check that doesn't require __typename
        return (line.merchandise?.product  &&
          line.merchandise?.product)?.hasTags?.some(tagResponse =>
            tagResponse.hasTag && tagResponse.tag === "perishable"
          );
      });
    
      if (!hasPerishableItem) return NO_CHANGES;
    
      // Find the free delivery option, comparing the cost to 0.0
      const deliveryOptions = deliveryGroups[0]?.deliveryOptions || [];
      const freeDeliveryOption = deliveryOptions.find(option =>
        parseFloat(option.cost?.amount) === 0
      );
    
      if (!freeDeliveryOption) return NO_CHANGES;
    
    
      // Hide the free delivery option
      return {
        operations: [
          {
            deliveryOptionHide: {
              deliveryOptionHandle: freeDeliveryOption.handle
            }
          }
        ]
      };
    }
    
    Performance Cost (JavaScript)

    322566 instructions

    Output JSON (Rust)
    {
        "operations": [
          {
            "deliveryOptionHide": {
              "deliveryOptionHandle": "dc4b9f18d30098469af5fabec87f3434-7bf1540a5810819fcc43fd9808d43db9"
            }
          }
        ]
      }
    
    Output JSON (JavaScript)
    {
        "operations": [
          {
            "deliveryOptionHide": {
              "deliveryOptionHandle": "dc4b9f18d30098469af5fabec87f3434-7bf1540a5810819fcc43fd9808d43db9"
            }
          }
        ]
      }
    
  • Hide express delivery options

    This function hides the express delivery option. This function hides a delivey or shipping option based off the title of the delivery option. The function demonstrates how to: * Read the title of the delivery option * Hide an operation if the conditions are met * Handle fields that are OPTIONAL in the input data

    cart.delivery-options.transform.run

    Input Query (Rust)
    query Input {
      cart {
        deliveryGroups {
          deliveryOptions {
            title # This is an OPTIONAL field in the input data. It doesn't have a ! at the end in the graphql schema
            handle # This is a REQUIRED field in the input data. It has a ! at the end in the graphql schema
          }
        }
      }
    }
    
    Input Query (JavaScript)
    query RunInput {
      cart {
        deliveryGroups {
          deliveryOptions {
            title
            handle
          }
        }
      }
    }
    
    Input Object (Rust)
    {
        "cart": {
          "deliveryGroups": [
            {
              "deliveryOptions": [
                {
                  "title": "Standard",
                  "handle": "dc4b9f18d30098469af5fabec87f3434-8ba6623428c2b6265e1f65c5f46491e3"
                },
                {
                  "title": "Supper express rate",
                  "handle": "dc4b9f18d30098469af5fabec87f3434-b514e01af8655a9229f7a04405396118"
                },
                {
                  "title": "Medium Rate",
                  "handle": "dc4b9f18d30098469af5fabec87f3434-fbcaff8dd39a68820109eb990460be0a"
                },
                {
                  "title": "Express",
                  "handle": "dc4b9f18d30098469af5fabec87f3434-4532dee4e5910fc249cd1d930c14e2c4"
                }
              ]
            }
          ]
        }
      }
    
    Input Object (JavaScript)
    {
        "cart": {
          "deliveryGroups": [
            {
              "deliveryOptions": [
                {
                  "title": "Standard",
                  "handle": "dc4b9f18d30098469af5fabec87f3434-8ba6623428c2b6265e1f65c5f46491e3"
                },
                {
                  "title": "Supper express rate",
                  "handle": "dc4b9f18d30098469af5fabec87f3434-b514e01af8655a9229f7a04405396118"
                },
                {
                  "title": "Medium Rate",
                  "handle": "dc4b9f18d30098469af5fabec87f3434-fbcaff8dd39a68820109eb990460be0a"
                },
                {
                  "title": "Express",
                  "handle": "dc4b9f18d30098469af5fabec87f3434-4532dee4e5910fc249cd1d930c14e2c4"
                }
              ]
            }
          ]
        }
      }
    
    Function Code (Rust)
    use crate::schema;
    use shopify_function::prelude::*;
    use shopify_function::Result;
    
    #[shopify_function]
    fn cart_delivery_options_transform_run(
        input: schema::cart_delivery_options_transform_run::Input,
    ) -> Result<schema::CartDeliveryOptionsTransformRunResult> {
        let mut operations = vec![];
    
        // Process each delivery group
        let cart = &input.cart();
        for group in cart.delivery_groups() {
            for option in group.delivery_options() {
                // The title field is optional in GraphQL (no ! suffix), so it's wrapped as Option<String> in Rust
                // Using as_ref() to avoid taking ownership of the String inside the Option
                // This converts Option<String> to Option<&String> so we can operate on its contents
                // map_or() handles both cases: provides false if None, or applies the function if Some
                let is_express = option
                    .title()
                    .as_ref()
                    .map_or(false, |t| t.to_lowercase().contains("express"));
    
                if is_express {
                    operations.push(schema::Operation::DeliveryOptionHide(
                        schema::DeliveryOptionHideOperation {
                            delivery_option_handle: option.handle().clone(),
                        },
                    ));
                }
            }
        }
    
        // If no operations were created, return empty operations
        Ok(schema::CartDeliveryOptionsTransformRunResult { operations })
    }
    
    Performance Cost (Rust)

    42067 instructions

    Function Code (JavaScript)
    // @ts-check
    
    /**
     * @typedef {import("../generated/api").RunInput} RunInput
     * @typedef {import("../generated/api").CartDeliveryOptionsTransformRunResult} CartDeliveryOptionsTransformRunResult
     */
    
    /**
     * @type {CartDeliveryOptionsTransformRunResult}
     */
    const NO_CHANGES = {
      operations: [],
    };
    
    /**
     * @param {RunInput} input
     * @returns {CartDeliveryOptionsTransformRunResult}
     */
    export function cartDeliveryOptionsTransformRun(input) {
    
      // Find any delivery options with the name "Express" and hide them
      const operations = [];
    
      // Process each delivery group
      if (input.cart?.deliveryGroups) {
        input.cart.deliveryGroups.forEach(group => {
          // Find any delivery options with the name "Express" and add hide operations for them
          if (group.deliveryOptions) {
            group.deliveryOptions.forEach(option => {
              if (option.title && option.title.toLowerCase().includes("express")) {
                operations.push({
                  deliveryOptionHide: {
                    deliveryOptionHandle: option.handle
                  }
                });
              }
            });
          }
        });
      }
    
      // If no operations were created, return NO_CHANGES
      if (operations.length === 0) {
        return NO_CHANGES;
      }
    
      // Return the operations to hide Express delivery options
      return {
        operations
      };
    };
    
    Performance Cost (JavaScript)

    227367 instructions

    Output JSON (Rust)
    {
        "operations": [
          {
            "deliveryOptionHide": {
              "deliveryOptionHandle": "dc4b9f18d30098469af5fabec87f3434-b514e01af8655a9229f7a04405396118"
            }
          },
          {
            "deliveryOptionHide": {
              "deliveryOptionHandle": "dc4b9f18d30098469af5fabec87f3434-4532dee4e5910fc249cd1d930c14e2c4"
            }
          }
        ]
      }
    
    Output JSON (JavaScript)
    {
        "operations": [
          {
            "deliveryOptionHide": {
              "deliveryOptionHandle": "dc4b9f18d30098469af5fabec87f3434-b514e01af8655a9229f7a04405396118"
            }
          },
          {
            "deliveryOptionHide": {
              "deliveryOptionHandle": "dc4b9f18d30098469af5fabec87f3434-4532dee4e5910fc249cd1d930c14e2c4"
            }
          }
        ]
      }
    
  • Add delivery timeframes to express shipping

    This function renames the express delivery option, to append the shipping timeline. The function demonstrates how to: * Read the title of the delivery option * Rename an operation if the conditions are met * Handle fields that are OPTIONAL in the input data

    cart.delivery-options.transform.run

    Input Query (Rust)
    query Input {
      cart {
        deliveryGroups {
          deliveryOptions {
            title # This is an OPTIONAL field in the input data. It does not have a ! at the end in the schema.
            handle # This is a REQUIRED field in the input data. It has a ! at the end in the schema.
          }
        }
      }
    }
    
    Input Query (JavaScript)
    query RunInput {
      cart {
        deliveryGroups {
          deliveryOptions {
            title
            handle
          }
        }
      }
    }
    
    Input Object (Rust)
    {
        "cart": {
          "deliveryGroups": [
            {
              "deliveryOptions": [
                {
                  "title": "Standard",
                  "handle": "dc4b9f18d30098469af5fabec87f3434-8ba6623428c2b6265e1f65c5f46491e3"
                },
                {
                  "title": "Supper express rate",
                  "handle": "dc4b9f18d30098469af5fabec87f3434-b514e01af8655a9229f7a04405396118"
                },
                {
                  "title": "Medium Rate",
                  "handle": "dc4b9f18d30098469af5fabec87f3434-fbcaff8dd39a68820109eb990460be0a"
                },
                {
                  "title": "Express",
                  "handle": "dc4b9f18d30098469af5fabec87f3434-4532dee4e5910fc249cd1d930c14e2c4"
                }
              ]
            }
          ]
        }
      }
    
    Input Object (JavaScript)
    {
        "cart": {
          "deliveryGroups": [
            {
              "deliveryOptions": [
                {
                  "title": "Standard",
                  "handle": "dc4b9f18d30098469af5fabec87f3434-8ba6623428c2b6265e1f65c5f46491e3"
                },
                {
                  "title": "Supper express rate",
                  "handle": "dc4b9f18d30098469af5fabec87f3434-b514e01af8655a9229f7a04405396118"
                },
                {
                  "title": "Medium Rate",
                  "handle": "dc4b9f18d30098469af5fabec87f3434-fbcaff8dd39a68820109eb990460be0a"
                },
                {
                  "title": "Express",
                  "handle": "dc4b9f18d30098469af5fabec87f3434-4532dee4e5910fc249cd1d930c14e2c4"
                }
              ]
            }
          ]
        }
      }
    
    Function Code (Rust)
    use crate::schema;
    use shopify_function::prelude::*;
    use shopify_function::Result;
    
    #[shopify_function]
    fn cart_delivery_options_transform_run(
        input: schema::cart_delivery_options_transform_run::Input,
    ) -> Result<schema::CartDeliveryOptionsTransformRunResult> {
        let no_changes = schema::CartDeliveryOptionsTransformRunResult { operations: vec![] };
    
        let mut operations = Vec::new();
    
        // Process each delivery group
        let cart = &input.cart();
        if cart.delivery_groups().is_empty() {
            return Ok(no_changes);
        }
    
        for group in cart.delivery_groups() {
            for option in group.delivery_options() {
                // Rust uses Option<T> to handle nullable values safely without null pointer exceptions
                // Option<String> means the title might exist (Some(String)) or be absent (None)
                // Using "if let Some(title)" is the idiomatic way to:
                // 1. Check if the value exists
                // 2. Unwrap it safely in one operation
                // 3. Only execute the code block if it exists, avoiding runtime errors
                if let Some(title) = option.title() {
                    if title.to_lowercase().contains("express") {
                        // Use enum variant construction
                        let rename_op = schema::DeliveryOptionRenameOperation {
                            delivery_option_handle: option.handle().clone(),
                            title: format!("{} (1-2 days)", title),
                        };
    
                        operations.push(schema::Operation::DeliveryOptionRename(rename_op));
                    }
                }
            }
        }
    
        // If no operations were created, return no_changes
        if operations.is_empty() {
            return Ok(no_changes);
        }
    
        // Return the operations to rename Express delivery options
        Ok(schema::CartDeliveryOptionsTransformRunResult { operations })
    }
    
    Performance Cost (Rust)

    46002 instructions

    Function Code (JavaScript)
    // @ts-check
    
    /**
     * @typedef {import("../generated/api").RunInput} RunInput
     * @typedef {import("../generated/api").CartDeliveryOptionsTransformRunResult} CartDeliveryOptionsTransformRunResult
     */
    
    /**
     * @type {CartDeliveryOptionsTransformRunResult}
     */
    const NO_CHANGES = {
      operations: [],
    };
    
    /**
     * @param {RunInput} input
     * @returns {CartDeliveryOptionsTransformRunResult}
     */
    export function cartDeliveryOptionsTransformRun(input) {
    
      // Find any delivery options with the name "Express" and rename them
      const operations = [];
    
      // Process each delivery group
      if (input.cart?.deliveryGroups) {
        input.cart.deliveryGroups.forEach(group => {
          // Find any delivery options with the name "Express" and add rename operations for them
          if (group.deliveryOptions) {
            group.deliveryOptions.forEach(option => {
              if (option.title && option.title.toLowerCase().includes("express")) {
                operations.push({
                  deliveryOptionRename: {
                    deliveryOptionHandle: option.handle,
                    title: `${option.title} (1-2 days)`
                  }
                });
              }
            });
          }
        });
      }
    
      // If no operations were created, return NO_CHANGES
      if (operations.length === 0) {
        return NO_CHANGES;
      }
    
      // Return the operations to rename Express delivery options
      return {
        operations
      };
    };
    
    Performance Cost (JavaScript)

    245120 instructions

    Output JSON (Rust)
    {
        "operations": [
          {
            "deliveryOptionRename": {
              "deliveryOptionHandle": "dc4b9f18d30098469af5fabec87f3434-b514e01af8655a9229f7a04405396118",
              "title": "Supper express rate (1-2 days)"
            }
          },
          {
            "deliveryOptionRename": {
              "deliveryOptionHandle": "dc4b9f18d30098469af5fabec87f3434-4532dee4e5910fc249cd1d930c14e2c4",
              "title": "Express (1-2 days)"
            }
          }
        ]
      }
    
    Output JSON (JavaScript)
    {
        "operations": [
          {
            "deliveryOptionRename": {
              "deliveryOptionHandle": "dc4b9f18d30098469af5fabec87f3434-b514e01af8655a9229f7a04405396118",
              "title": "Supper express rate (1-2 days)"
            }
          },
          {
            "deliveryOptionRename": {
              "deliveryOptionHandle": "dc4b9f18d30098469af5fabec87f3434-4532dee4e5910fc249cd1d930c14e2c4",
              "title": "Express (1-2 days)"
            }
          }
        ]
      }
    
  • Hide shipping options by zip code using metaobjects

    An example delivery customization function that hides specific shipping methods when the buyer's zip code is on a restricted list. The restricted zip codes and the delivery option to hide are stored in a shop-level metaobject (using the 2026-04 Shop.metaobject field) with typed fields — a list.single_line_text_field for zip codes and a single_line_text_field for the delivery option title. The merchant can update restrictions by editing the metaobject entry in the Shopify admin — no code changes required.

    cart.delivery-options.transform.run

    Input Query (Rust)
    query Input {
      shop {
        restrictionConfig: metaobject(handle: { type: "$app:shipping_restriction", handle: "default" }) {
          restrictedZipCodes: field(key: "restricted_zip_codes") {
            jsonValue
          }
          hiddenDeliveryOptionTitle: field(key: "hidden_delivery_option_title") {
            value
          }
        }
      }
      cart {
        deliveryGroups {
          deliveryAddress {
            zip
          }
          deliveryOptions {
            title
            handle
            cost {
              amount
            }
          }
        }
      }
    }
    
    Input Query (JavaScript)
    query Input {
      shop {
        restrictionConfig: metaobject(handle: { type: "$app:shipping_restriction", handle: "default" }) {
          restrictedZipCodes: field(key: "restricted_zip_codes") {
            jsonValue
          }
          hiddenDeliveryOptionTitle: field(key: "hidden_delivery_option_title") {
            value
          }
        }
      }
      cart {
        deliveryGroups {
          deliveryAddress {
            zip
          }
          deliveryOptions {
            title
            handle
            cost {
              amount
            }
          }
        }
      }
    }
    
    Input Object (Rust)
    {
      "shop": {
        "restrictionConfig": {
          "restrictedZipCodes": {
            "jsonValue": [
              "90210",
              "10001"
            ]
          },
          "hiddenDeliveryOptionTitle": {
            "value": "Express Shipping"
          }
        }
      },
      "cart": {
        "deliveryGroups": [
          {
            "deliveryAddress": {
              "zip": "90210"
            },
            "deliveryOptions": [
              {
                "title": "Standard Shipping",
                "handle": "standard-shipping",
                "cost": {
                  "amount": "5.00"
                }
              },
              {
                "title": "Express Shipping",
                "handle": "express-shipping",
                "cost": {
                  "amount": "15.00"
                }
              }
            ]
          }
        ]
      }
    }
    
    Input Object (JavaScript)
    {
      "shop": {
        "restrictionConfig": {
          "restrictedZipCodes": {
            "jsonValue": [
              "90210",
              "10001"
            ]
          },
          "hiddenDeliveryOptionTitle": {
            "value": "Express Shipping"
          }
        }
      },
      "cart": {
        "deliveryGroups": [
          {
            "deliveryAddress": {
              "zip": "90210"
            },
            "deliveryOptions": [
              {
                "title": "Standard Shipping",
                "handle": "standard-shipping",
                "cost": {
                  "amount": "5.00"
                }
              },
              {
                "title": "Express Shipping",
                "handle": "express-shipping",
                "cost": {
                  "amount": "15.00"
                }
              }
            ]
          }
        ]
      }
    }
    
    Function Code (Rust)
    use crate::schema;
    use shopify_function::prelude::*;
    use shopify_function::scalars::JsonValue;
    use shopify_function::Result;
    
    fn json_value_to_string_vec(value: &JsonValue) -> Vec<String> {
        match value {
            JsonValue::Array(items) => items
                .iter()
                .filter_map(|item| match item {
                    JsonValue::String(s) => Some(s.clone()),
                    _ => None,
                })
                .collect(),
            _ => vec![],
        }
    }
    
    #[shopify_function]
    fn cart_delivery_options_transform_run(
        input: schema::cart_delivery_options_transform_run::Input,
    ) -> Result<schema::CartDeliveryOptionsTransformRunResult> {
        let restriction_config = match input.shop().restriction_config() {
            Some(config) => config,
            None => {
                return Ok(schema::CartDeliveryOptionsTransformRunResult {
                    operations: vec![],
                })
            }
        };
    
        // Read typed metaobject fields
        let restricted_zip_codes: Vec<String> = restriction_config
            .restricted_zip_codes()
            .and_then(|f| f.json_value())
            .map(json_value_to_string_vec)
            .unwrap_or_default();
    
        let hidden_title = match restriction_config.hidden_delivery_option_title() {
            Some(field) => match field.value() {
                Some(v) => v.clone(),
                None => {
                    return Ok(schema::CartDeliveryOptionsTransformRunResult {
                        operations: vec![],
                    })
                }
            },
            None => {
                return Ok(schema::CartDeliveryOptionsTransformRunResult {
                    operations: vec![],
                })
            }
        };
    
        if restricted_zip_codes.is_empty() {
            return Ok(schema::CartDeliveryOptionsTransformRunResult {
                operations: vec![],
            });
        }
    
        let delivery_groups = input.cart().delivery_groups();
        if delivery_groups.is_empty() {
            return Ok(schema::CartDeliveryOptionsTransformRunResult {
                operations: vec![],
            });
        }
    
        let buyer_zip = match delivery_groups[0].delivery_address() {
            Some(address) => match address.zip() {
                Some(zip) => zip.to_string(),
                None => {
                    return Ok(schema::CartDeliveryOptionsTransformRunResult {
                        operations: vec![],
                    })
                }
            },
            None => {
                return Ok(schema::CartDeliveryOptionsTransformRunResult {
                    operations: vec![],
                })
            }
        };
    
        if !restricted_zip_codes.contains(&buyer_zip) {
            return Ok(schema::CartDeliveryOptionsTransformRunResult {
                operations: vec![],
            });
        }
    
        // Match by title, then use the handle to hide the option
        let matched_handle = delivery_groups[0]
            .delivery_options()
            .iter()
            .find(|opt| opt.title().map(|t| t.as_str()) == Some(hidden_title.as_str()))
            .map(|opt| opt.handle().to_string());
    
        match matched_handle {
            Some(handle) => Ok(schema::CartDeliveryOptionsTransformRunResult {
                operations: vec![
                    schema::Operation::DeliveryOptionHide(
                        schema::DeliveryOptionHideOperation {
                            delivery_option_handle: handle,
                        },
                    ),
                ],
            }),
            None => Ok(schema::CartDeliveryOptionsTransformRunResult {
                operations: vec![],
            }),
        }
    }
    
    Performance Cost (Rust)

    38350 instructions

    Function Code (JavaScript)
    // @ts-check
    
    /**
     * @typedef {import("../generated/api").RunInput} RunInput
     * @typedef {import("../generated/api").CartDeliveryOptionsTransformRunResult} CartDeliveryOptionsTransformRunResult
     */
    
    /**
     * @type {CartDeliveryOptionsTransformRunResult}
     */
    const NO_CHANGES = {
      operations: [],
    };
    
    /**
     * @param {RunInput} input
     * @returns {CartDeliveryOptionsTransformRunResult}
     */
    export function cartDeliveryOptionsTransformRun(input) {
      const restrictionConfig = input.shop?.restrictionConfig;
      if (!restrictionConfig) {
        return NO_CHANGES;
      }
    
      // Read typed metaobject fields — no JSON parsing needed
      const restrictedZipCodes = restrictionConfig.restrictedZipCodes?.jsonValue ?? [];
      const hiddenTitle = restrictionConfig.hiddenDeliveryOptionTitle?.value;
    
      if (restrictedZipCodes.length === 0 || !hiddenTitle) {
        return NO_CHANGES;
      }
    
      const deliveryGroups = input.cart?.deliveryGroups ?? [];
      if (deliveryGroups.length === 0) {
        return NO_CHANGES;
      }
    
      const buyerZip = deliveryGroups[0]?.deliveryAddress?.zip;
      if (!buyerZip || !restrictedZipCodes.includes(buyerZip)) {
        return NO_CHANGES;
      }
    
      // Match the delivery option by title, then use its handle to hide it
      const deliveryOptions = deliveryGroups[0]?.deliveryOptions ?? [];
      const matchedOption = deliveryOptions.find(
        (option) => option.title === hiddenTitle
      );
    
      if (!matchedOption) {
        return NO_CHANGES;
      }
    
      return {
        operations: [
          {
            deliveryOptionHide: {
              deliveryOptionHandle: matchedOption.handle,
            },
          },
        ],
      };
    }
    
    Performance Cost (JavaScript)

    225690 instructions

    Output JSON (Rust)
    {
      "operations": [
        {
          "deliveryOptionHide": {
            "deliveryOptionHandle": "express-shipping"
          }
        }
      ]
    }
    
    Output JSON (JavaScript)
    {
      "operations": [
        {
          "deliveryOptionHide": {
            "deliveryOptionHandle": "express-shipping"
          }
        }
      ]
    }
    
  • Rename delivery methods with province-specific messages

    This function renames a delivery method to include additional message based on province such as weather delays.

    cart.delivery-options.transform.run

    Input Query (Rust)
    query Input {
      cart {
        deliveryGroups {
          deliveryAddress {
            provinceCode
          }
          deliveryOptions {
            handle
            title
          }
        }
      }
      deliveryCustomization {
        metafield(namespace: "$app:delivery-customization", key: "configuration") {
          jsonValue
        }
      }
    }
    
    Input Query (JavaScript)
    query RunInput {
      cart {
        deliveryGroups {
          deliveryAddress {
            provinceCode
          }
          deliveryOptions {
            handle
            title
          }
        }
      }
      deliveryCustomization {
        metafield(namespace: "$app:delivery-customization", key: "configuration") {
          jsonValue
        }
      }
    }
    
    Input Object (Rust)
    {
      "cart": {
        "deliveryGroups": [
          {
            "deliveryAddress": {
              "provinceCode": "NC"
            },
            "deliveryOptions": [
              {
                "handle": "standard_shipping",
                "title": "Standard Shipping"
              }
            ]
          }
        ]
      },
      "deliveryCustomization": {
        "metafield": {
          "jsonValue": {
            "provinces": [
              {
                "province_code": "NC",
                "message": "May be delayed due to weather conditions"
              },
              {
                "province_code": "FL",
                "message": "Hurricane warning - expect delays"
              }
            ]
          }
        }
      }
    }
    
    Input Object (JavaScript)
    {
      "cart": {
        "deliveryGroups": [
          {
            "deliveryAddress": {
              "provinceCode": "NC"
            },
            "deliveryOptions": [
              {
                "handle": "standard_shipping",
                "title": "Standard Shipping"
              }
            ]
          }
        ]
      },
      "deliveryCustomization": {
        "metafield": {
          "jsonValue": {
            "provinces": [
              {
                "province_code": "NC",
                "message": "May be delayed due to weather conditions"
              },
              {
                "province_code": "FL",
                "message": "Hurricane warning - expect delays"
              }
            ]
          }
        }
      }
    }
    
    Function Code (Rust)
    use crate::schema;
    use shopify_function::prelude::*;
    use shopify_function::Result;
    
    #[derive(Deserialize, Default, PartialEq)]
    pub struct ProvinceConfig {
        province_code: String,
        message: String,
    }
    
    #[derive(Deserialize, Default, PartialEq)]
    pub struct Configuration {
        provinces: Vec<ProvinceConfig>,
    }
    
    // The configured entrypoint for the 'purchase.delivery-customization.run' extension target
    #[shopify_function]
    fn cart_delivery_options_transform_run(
        input: schema::cart_delivery_options_transform_run::Input,
    ) -> Result<schema::CartDeliveryOptionsTransformRunResult> {
        let config = match input.delivery_customization().metafield() {
            Some(metafield) => metafield.json_value(),
            None => &Configuration::default(),
        };
    
        let to_rename = input
            .cart()
            .delivery_groups()
            .iter()
            // Filter for delivery groups with a shipping address containing the affected province
            .filter_map(|group| {
                let province_code = group
                    .delivery_address()
                    .as_ref()
                    .and_then(|address| address.province_code())?;
    
                // Find matching configuration for the province
                let province_config = config
                    .provinces
                    .iter()
                    .find(|config| &config.province_code == province_code)?;
    
                Some((group, &province_config.message))
            })
            // Collect the delivery options from these groups
            .flat_map(|(group, message)| {
                group.delivery_options().iter().map(move |option| {
                    schema::DeliveryOptionRenameOperation {
                        delivery_option_handle: option.handle().to_string(),
                        title: match &option.title() {
                            Some(title) => format!("{} - {}", title, message),
                            None => message.to_string(),
                        },
                    }
                })
            })
            // Wrap with an Operation
            .map(schema::Operation::DeliveryOptionRename)
            .collect();
    
        Ok(schema::CartDeliveryOptionsTransformRunResult {
            operations: to_rename,
        })
    }
    
    Performance Cost (Rust)

    46140 instructions

    Function Code (JavaScript)
    // @ts-check
    
    /**
     * @typedef {import("../generated/api").RunInput} RunInput
     * @typedef {import("../generated/api").CartDeliveryOptionsTransformRunResult} CartDeliveryOptionsTransformRunResult
     * @typedef {import("../generated/api").Operation} Operation
     * @typedef {import("../generated/api").DeliveryOptionRenameOperation} DeliveryOptionRenameOperation
     */
    
    /**
     * @typedef {Object} ProvinceConfig
     * @property {string} province_code
     * @property {string} message
     */
    
    /**
     * @typedef {Object} Configuration
     * @property {ProvinceConfig[]} provinces
     */
    
    /**
     * @type {CartDeliveryOptionsTransformRunResult}
     */
    const NO_CHANGES = {
      operations: [],
    };
    
    /**
     * @param {RunInput} input
     * @returns {CartDeliveryOptionsTransformRunResult}
     */
    export function cartDeliveryOptionsTransformRun(input) {
      // Get configuration or return empty result if no metafield is set
      if (!input?.deliveryCustomization?.metafield) {
        return NO_CHANGES;
      }
    
      /** @type {Configuration} */
      const configuration = input.deliveryCustomization.metafield.jsonValue;
      if (!configuration?.provinces) {
        return NO_CHANGES;
      }
    
      /** @type {Operation[]} */
      const operations = input.cart.deliveryGroups
        .flatMap(group => {
          const provinceCode = group.deliveryAddress?.provinceCode;
          if (!provinceCode) return [];
    
          // Find matching configuration for the province
          const provinceConfig = configuration.provinces.find(
            config => config.province_code === provinceCode
          );
          if (!provinceConfig) return [];
    
          // Map each delivery option to a rename operation
          return group.deliveryOptions.map(option => ({
            deliveryOptionRename: {
              deliveryOptionHandle: option.handle,
              title: option.title
                ? `${option.title} - ${provinceConfig.message}`
                : provinceConfig.message
            }
          }));
        });
    
      return {
        operations
      };
    }
    
    Performance Cost (JavaScript)

    238970 instructions

    Output JSON (Rust)
    {
      "operations": [
        {
          "deliveryOptionRename": {
            "deliveryOptionHandle": "standard_shipping",
            "title": "Standard Shipping - May be delayed due to weather conditions"
          }
        }
      ]
    }
    
    Output JSON (JavaScript)
    {
      "operations": [
        {
          "deliveryOptionRename": {
            "deliveryOptionHandle": "standard_shipping",
            "title": "Standard Shipping - May be delayed due to weather conditions"
          }
        }
      ]
    }
    
  • Hide delivery methods based on customer tags

    This example implements a Shopify function that hides certain delivery methods based on the buyer's tag which is configurable by an app owned metafield.

    cart.delivery-options.transform.run

    Input Query (Rust)
    query Input($tags: [String!]! = ["Gold"]) {
      cart {
        buyerIdentity {
          customer {
            hasTags(tags: $tags) {
              tag
              hasTag
            }
          }
        }
        deliveryGroups {
          id
          deliveryOptions {
            handle
            title
          }
        }
      }
      deliveryCustomization {
        metafield(namespace: "$app:delivery-customization", key: "configuration") {
          jsonValue
        }
      }
    }
    
    Input Query (JavaScript)
    query RunInput($tags: [String!]! = ["Gold"]) {
      cart {
        buyerIdentity {
          customer {
            hasTags(tags: $tags) {
              tag
              hasTag
            }
          }
        }
        deliveryGroups {
          id
          deliveryOptions {
            handle
            title
          }
        }
      }
      deliveryCustomization {
        metafield(namespace: "$app:delivery-customization", key: "configuration") {
          jsonValue
        }
      }
    }
    
    Input Object (Rust)
    {
      "cart": {
        "buyerIdentity": {
          "customer": {
            "hasTags": [
              {
                "tag": "VIP",
                "hasTag": true
              }
            ]
          }
        },
        "deliveryGroups": [
          {
            "id": "gid://shopify/CartDeliveryGroup/0",
            "deliveryOptions": [
              {
                "handle": "standard-shipping",
                "title": "Standard Shipping"
              },
              {
                "handle": "express-shipping",
                "title": "Express Shipping"
              }
            ]
          }
        ]
      },
      "deliveryCustomization": {
        "metafield": {
          "jsonValue": {
            "hiddenDeliveryOptions": {
              "VIP": [
                "express-shipping"
              ]
            }
          }
        }
      }
    }
    
    Input Object (JavaScript)
    {
      "cart": {
        "buyerIdentity": {
          "customer": {
            "hasTags": [
              {
                "tag": "VIP",
                "hasTag": true
              }
            ]
          }
        },
        "deliveryGroups": [
          {
            "id": "gid://shopify/CartDeliveryGroup/0",
            "deliveryOptions": [
              {
                "handle": "standard-shipping",
                "title": "Standard Shipping"
              },
              {
                "handle": "express-shipping",
                "title": "Express Shipping"
              }
            ]
          }
        ]
      },
      "deliveryCustomization": {
        "metafield": {
          "jsonValue": {
            "hiddenDeliveryOptions": {
              "VIP": [
                "express-shipping"
              ]
            }
          }
        }
      }
    }
    
    Function Code (Rust)
    use crate::schema;
    use shopify_function::prelude::*;
    use shopify_function::Result;
    use std::collections::HashMap;
    
    #[derive(Deserialize, Default, PartialEq)]
    #[shopify_function(rename_all = "camelCase")]
    pub struct Configuration {
        hidden_delivery_options: HashMap<String, Vec<String>>,
    }
    
    #[shopify_function]
    fn cart_delivery_options_transform_run(
        input: schema::cart_delivery_options_transform_run::Input,
    ) -> Result<schema::CartDeliveryOptionsTransformRunResult> {
        let config: &Configuration = match input.delivery_customization().metafield() {
            Some(metafield) => metafield.json_value(),
            None => return Ok(schema::CartDeliveryOptionsTransformRunResult { operations: vec![] }),
        };
    
        let buyer_tags = input
            .cart()
            .buyer_identity()
            .and_then(|identity| identity.customer())
            .map(|customer| {
                customer
                    .has_tags()
                    .iter()
                    .filter(|tag_info| *tag_info.has_tag())
                    .map(|tag_info| tag_info.tag().clone())
                    .collect::<Vec<String>>()
            })
            .unwrap_or_default();
    
        let mut operations = vec![];
    
        for tag in buyer_tags {
            if let Some(hidden_options) = config.hidden_delivery_options.get(&tag) {
                for handle in hidden_options {
                    operations.push(schema::Operation::DeliveryOptionHide(
                        schema::DeliveryOptionHideOperation {
                            delivery_option_handle: handle.clone(),
                        },
                    ));
                }
            }
        }
    
        Ok(schema::CartDeliveryOptionsTransformRunResult { operations })
    }
    
    Performance Cost (Rust)

    40331 instructions

    Function Code (JavaScript)
    // @ts-check
    
    /**
     * @typedef {import("../generated/api").RunInput} RunInput
     * @typedef {import("../generated/api").CartDeliveryOptionsTransformRunResult} CartDeliveryOptionsTransformRunResult
     * @typedef {import("../generated/api").DeliveryOptionHideOperation} DeliveryOptionHideOperation
     */
    
    /**
     * @type {CartDeliveryOptionsTransformRunResult}
     */
    const NO_CHANGES = {
      operations: [],
    };
    
    /**
     * @param {RunInput} input
     * @returns {CartDeliveryOptionsTransformRunResult}
     */
    export function cartDeliveryOptionsTransformRun(input) {
      // If no metafield exists, return no changes
      if (!input?.deliveryCustomization?.metafield?.jsonValue) {
        return NO_CHANGES;
      }
    
      // Parse the configuration from metafield
      const configuration = input.deliveryCustomization.metafield.jsonValue;
      const hiddenDeliveryOptions = configuration.hiddenDeliveryOptions || {};
    
      // Get customer tags that are true
      const buyerTags = input.cart?.buyerIdentity?.customer?.hasTags
        ?.filter(tagInfo => tagInfo.hasTag)
        .map(tagInfo => tagInfo.tag) || [];
    
      // Create operations array for hiding delivery options
      const operations = [];
    
      // For each buyer tag, check if there are delivery options to hide
      for (const tag of buyerTags) {
        const hiddenOptions = hiddenDeliveryOptions[tag] || [];
        for (const handle of hiddenOptions) {
          operations.push({
            deliveryOptionHide: {
              deliveryOptionHandle: handle
            }
          });
        }
      }
    
      return { operations };
    }
    
    Performance Cost (JavaScript)

    242601 instructions

    Output JSON (Rust)
    {
      "operations": [
        {
          "deliveryOptionHide": {
            "deliveryOptionHandle": "express-shipping"
          }
        }
      ]
    }
    
    Output JSON (JavaScript)
    {
      "operations": [
        {
          "deliveryOptionHide": {
            "deliveryOptionHandle": "express-shipping"
          }
        }
      ]
    }
    
  • Reposition a premium delivery option

    This functions moves the most expensive delivery, (shipping) option to the second position from the top of the list, when displayed to customers. The example demonstrates how to: * determine the price of each delivery option * re-order the delivery options * re-order the delivery options based on price

    cart.delivery-options.transform.run

    Input Query (Rust)
    query Input {
      cart {
        deliveryGroups {
          deliveryOptions {
            handle
            cost {
              amount
            }
          }
        }
      }
    }
    
    Input Query (JavaScript)
    query RunInput {
      cart {
        deliveryGroups {
          deliveryOptions {
            handle
            cost {
              amount
            }
          }
        }
      }
    }
    
    Input Object (Rust)
    {
        "cart": {
          "deliveryGroups": [
            {
              "deliveryOptions": [
                {
                  "handle": "dc4b9f18d30098469af5fabec87f3434-7bf1540a5810819fcc43fd9808d43db9",
                  "cost": {
                    "amount": "0.0"
                  }
                },
                {
                  "handle": "dc4b9f18d30098469af5fabec87f3434-b514e01af8655a9229f7a04405396118",
                  "cost": {
                    "amount": "1.0"
                  }
                },
                {
                  "handle": "dc4b9f18d30098469af5fabec87f3434-fbcaff8dd39a68820109eb990460be0a",
                  "cost": {
                    "amount": "15.0"
                  }
                }
              ]
            }
          ]
        }
      }
    
    Input Object (JavaScript)
    {
        "cart": {
          "deliveryGroups": [
            {
              "deliveryOptions": [
                {
                  "handle": "dc4b9f18d30098469af5fabec87f3434-7bf1540a5810819fcc43fd9808d43db9",
                  "cost": {
                    "amount": "0.0"
                  }
                },
                {
                  "handle": "dc4b9f18d30098469af5fabec87f3434-b514e01af8655a9229f7a04405396118",
                  "cost": {
                    "amount": "1.0"
                  }
                },
                {
                  "handle": "dc4b9f18d30098469af5fabec87f3434-fbcaff8dd39a68820109eb990460be0a",
                  "cost": {
                    "amount": "15.0"
                  }
                }
              ]
            }
          ]
        }
      }
    
    Function Code (Rust)
    use crate::schema;
    use shopify_function::prelude::*;
    use shopify_function::Result;
    
    #[shopify_function]
    fn cart_delivery_options_transform_run(
        input: schema::cart_delivery_options_transform_run::Input,
    ) -> Result<schema::CartDeliveryOptionsTransformRunResult> {
        // Initialize with no operations
        let mut operations = vec![];
    
        // Find the most expensive delivery option across all delivery groups
        // Look at all the prices of the delivery options
        let mut most_expensive_handle = None;
        let mut highest_cost = -1.0;
    
        for group in input.cart().delivery_groups() {
            for option in group.delivery_options() {
                let amount = option
                    .cost()
                    .amount()
                    .to_string()
                    .parse::<f64>()
                    .unwrap_or(-1.0);
                if amount > highest_cost {
                    highest_cost = amount;
                    most_expensive_handle = Some(option.handle().clone());
                }
            }
        }
    
        // If we found a most expensive option, add an operation to move it to index 1
        if let Some(handle) = most_expensive_handle {
            operations.push(schema::Operation::DeliveryOptionMove(
                schema::DeliveryOptionMoveOperation {
                    delivery_option_handle: handle,
                    index: 1, // The second position in the list
                },
            ));
        }
    
        Ok(schema::CartDeliveryOptionsTransformRunResult { operations })
    }
    
    Performance Cost (Rust)

    43010 instructions

    Function Code (JavaScript)
    // @ts-check
    
    // Use JSDoc annotations for type safety
    /**
    * @typedef {import("../generated/api").RunInput} RunInput
    * @typedef {import("../generated/api").CartDeliveryOptionsTransformRunResult} CartDeliveryOptionsTransformRunResult
    * @typedef {import("../generated/api").Operation} Operation
    */
    
    // The configured entrypoint for the 'purchase.delivery-customization.run' extension target
    /**
    * @param {RunInput} input
    * @returns {CartDeliveryOptionsTransformRunResult}
    */
    export function cartDeliveryOptionsTransformRun(input) {
      // Find the most expensive delivery option across all delivery groups
      let mostExpensiveHandle = null;
      let highestCost = -1;
    
      input.cart.deliveryGroups.forEach(group => {
        (group.deliveryOptions || []).forEach(option => {
          const cost = option.cost?.amount;
          if (cost !== undefined && cost > highestCost) {
            highestCost = cost;
            mostExpensiveHandle = option.handle;
          }
        });
      });
    
      // If we found a most expensive option, add an operation to move it to index 1
      const operations = [];
      if (mostExpensiveHandle) {
        /** @type {Operation} */
        const moveOperation = {
          deliveryOptionMove: {
            deliveryOptionHandle: mostExpensiveHandle,
            // The second position in the list
            index: 1
          }
        };
        operations.push(moveOperation);
      }
    
      return {
        operations
      };
    };
    
    Performance Cost (JavaScript)

    198050 instructions

    Output JSON (Rust)
    {
        "operations": [
            {
                "deliveryOptionMove": {
                    "deliveryOptionHandle": "dc4b9f18d30098469af5fabec87f3434-fbcaff8dd39a68820109eb990460be0a",
                    "index": 1
                }
            }
        ]
    }
    
    Output JSON (JavaScript)
    {
        "operations": [
            {
                "deliveryOptionMove": {
                    "deliveryOptionHandle": "dc4b9f18d30098469af5fabec87f3434-fbcaff8dd39a68820109eb990460be0a",
                    "index": 1
                }
            }
        ]
    }
    

Migrating from Shopify Scripts to Shopify Functions

If you want to migrate an existing shipping script to Shopify Functions, then you can use the following mappings:

| Shopify Scripts method | Description | Shopify Functions operation | Additional context | | - | - | - | - | | change_name | Changes the name of a delivery option | deliveryOptionRename | The carrier name is automatically prepended to the delivery option title at checkout and can't be altered or omitted. For example, if the carrier name is UPS and the delivery option is Standard, then you could change UPS Standard to UPS Standard Shipping, but you couldn't change UPS Standard to Standard Shipping. | | sort | Sorts the delivery options based on some criteria, typically to place one delivery option at the top or bottom of a list | deliveryOptionMove | Moves delivery options instead of sorting them. When reordering shipping delivery options, you're prohibited from automatically selecting higher-priced delivery alternatives by default. The cheapest shipping delivery option must always be the first option selected. | | delete_if | Removes a delivery option from checkout | deliveryOptionHide | |


Additional resources

Explore comprehensive guides and references to help you build, deploy, and optimize your Shopify Functions.

Working with Functions

These guides cover essential concepts for building Shopify Functions effectively. Learn how functions process data, execute during checkout, and handle versioning, localization, and external APIs.

Function anatomy

Explore how functions process input data and generate operations.

Execution order in checkout

Learn when Function APIs execute during the checkout process.

Schema and versioning

Understand schema versioning, release and upgrade requirements.

API availability

Check which Shopify plans support functions in custom apps.

Localization practices

Localize functions for international markets.

Performance and troubleshooting

Optimize function performance and ensure reliable operation from development through production deployment.

Resource limits and performance

Understand function performance requirements and resource limitations for optimal execution.

Test and debug Shopify Functions

Explore comprehensive testing workflows from local development to production deployment.

Considerations for programming languages

Choose languages that compile to WebAssembly for optimal function performance.

Monitoring and handling errors in production

Master testing and debugging workflows for reliable function development.