---
title: Discounts with network access in custom storefronts
description: >-
  Learn how to integrate discount Functions with network calls into carts using
  the @defer directive.
source_url:
  html: 'https://shopify.dev/docs/apps/build/discounts/network-access-in-cart'
  md: 'https://shopify.dev/docs/apps/build/discounts/network-access-in-cart.md'
---

# Discounts with network access in custom storefronts

You can execute Functions with network calls in the Storefront API Cart. This guide explains how to use the `@defer` directive to handle asynchronous discount calculations.

**Shopify for enterprise:**

Network access for [Shopify Functions](https://shopify.dev/docs/apps/build/functions) is limited to [Shopify for enterprise](https://www.shopify.com/enterprise) plans. For more information, contact [our enterprise sales team](https://www.shopify.com/solutions/shop-pay/enterprise#contact-sales).

## What you'll learn

In this tutorial, you'll learn how to do the following tasks:

* Understand the requirements for Functions with network calls on custom storefronts.
* Use the `@defer` directive to handle asynchronous discount calculations.
* Structure GraphQL mutations for cart creation with deferred discount processing.
* Handle both immediate and deferred responses in your storefront implementation.
* Add discounts powered by a function with network access to a cart on a custom storefront.

## Requirements

[Have an app that is set up to make calls to the GraphQL Storefront API](https://shopify.dev/docs/storefronts/headless/building-with-the-storefront-api/cart/manage)

[Use the `@defer` directive](https://shopify.dev/docs/storefronts/headless/building-with-the-storefront-api/defer)

Since network calls are asynchronous, use Shopify's GraphQL `@defer` directive to handle asynchronous processes. If you don't use `@defer`, the network call won't execute.

[Scaffold an app with a Discount Function that has network access](https://shopify.dev/docs/apps/build/discounts/network-access)

To begin, follow the [Build a Discount Function that has network access](https://shopify.dev/docs/apps/build/discounts/network-access) tutorial, or build your own app and Discount Function using the [Discount API](https://shopify.dev/docs/apps/build/discounts).

## Project

[View on GitHub](https://github.com/Shopify/discounts-reference-app/blob/main/docs/reference/storefront)

After creating a [function with network access running in checkout](https://shopify.dev/docs/apps/build/discounts/network-access), you can set up your custom storefront to support buyers applying discounts to their carts.

## Craft your mutation

To create a cart and apply a discount, use a GraphQL mutation. The following mutation creates a cart, and uses `@defer` to fetch additional cart details asynchronously after the network call from the function completes.

### Understanding the mutation structure

* **Initial Response**: The cart is processed immediately and returns important information like the cart ID and checkout URL.
* **Deferred Response**: The `@defer` directive is applied to the `cart` field, which is defined with alias `asyncCart`. This means that the additional details regarding discount codes and allocations are fetched asynchronously when the network call is complete.

## Prepare your input

Next, prepare the input data for the mutation. This example includes the discount codes and the items to add to the cart. You can also add discount codes to the cart using the [`cartDiscountCodesUpdate` mutation](https://shopify.dev/docs/api/storefront/latest/mutations/cartDiscountCodesUpdate).

The list of `discountCodes` that you pass here behave the same as in checkout. They are passed to the input of the `fetch` target as the `enteredDiscountCodes` field.

## Execute the mutation

Use the [Shopify Storefront API JS Client](https://github.com/Shopify/shopify-app-js/tree/main/packages/api-clients/storefront-api-client) or [any client that supports multipart responses](https://shopify.dev/docs/storefronts/headless/building-with-the-storefront-api/defer#choosing-a-supported-client). The discount Function runs and applies valid discounts to the cart and relevant line items.

The response contains an initial cart response object (with the original costs and line items), followed by the `asyncCart` object that includes the updated cost amounts and the applied discount.

## Key considerations

* **Root-level requirement**: To run the Function with network calls, `@defer` must be used at the root level (cart) of the query. This ensures that the network call's outcome is used and considered for the whole cart object. If `@defer` isn't used at the root level, the network call doesn't execute.
* **Discount management**: Use `@defer` on every mutation that impacts pricing, to ensure that network calls are executed on subsequent updates as the cart changes (which may affect the application and eligibility of discounts).
* **Query structure**: If needed, you can query for the same fields in both the initial cart and the deferred cart. However, fields relying on discount application (such as `cost.totalAmount`) are only correct when calculated in the deferred response.
* **Execution of Functions on mutations**: The Function runs on every mutation that creates or updates a cart, but it doesn't run for queries.
* **Checkout behavior**: Functions with network calls execute when a buyer navigates to checkout, even if the cart API calls don't use the `@defer` directive.

## cartCreate.graphql

```graphql
mutation CartCreate($input: CartInput!) {
  cartCreate(input: $input) {
    cart {
      id
      checkoutUrl
      cost {
        subtotalAmount {
          amount
          currencyCode
        }
        totalAmount {
          amount
          currencyCode
        }
      }
      lines(first: 10) {
        nodes {
          quantity
          merchandise {
            ... on ProductVariant {
              title
            }
          }
        }
      }
    }
    userErrors {
      code
      field
      message
    }
    warnings {
      code
      target
      message
    }
    ... @defer {
      asyncCart: cart {
        cost {
          subtotalAmount {
            amount
            currencyCode
          }
          totalAmount {
            amount
            currencyCode
          }
        }
        lines(first: 10) {
          edges {
            node {
              merchandise {
                ... on ProductVariant {
                  title
                }
              }
              # Line-level discount
              discountAllocations {
                discountApplication {
                  allocationMethod
                  targetSelection
                }
                discountedAmount {
                  amount
                  currencyCode
                }
              }
            }
          }
        }
        discountCodes {
          applicable
          code
        }
        # Cart-level discount
        discountAllocations {
          discountApplication {
            allocationMethod
            targetSelection
          }
          discountedAmount {
            amount
            currencyCode
          }
        }
      }
    }
  }
}
```

## cartCreateInput.json

```json
{
  "input": {
    "discountCodes": ["10OFFPRODUCT"],
    "lines": [
      {
        "quantity": 2,
        "merchandiseId": "gid://shopify/ProductVariant/35610123173910"
      }
    ]
  }
}
```

## Tutorial complete!

You've successfully applied a network-powered discount to a cart. Now, update your storefront to display the discount details to the buyer.

***

### Next Steps

[Build a UI extension to configure your discount Function\
\
Add configuration to your discounts experience using metafields and build a user interface for your Function.](https://shopify.dev/docs/apps/build/discounts/build-ui-extension)[Build a React Router app to configure your discount Function\
\
Add configuration to your discounts experience using metafields and build a user interface for your Function.](https://shopify.dev/docs/apps/build/discounts/build-ui-with-react-router)[Review the UX guidelines\
\
Review the UX guidelines to learn how to implement discounts in user interfaces.](https://shopify.dev/docs/apps/build/discounts/ux-for-discounts)[Learn more about Shopify Functions\
\
Learn more about how Shopify Functions work and the benefits of using Shopify Functions.](https://shopify.dev/docs/apps/build/functions)[Consult the Shopify Functions API references\
\
Consult the API references for Shopify Functions](https://shopify.dev/docs/api/functions)[Learn more about deploying app versions\
\
Learn more about deploying app versions to Shopify](https://shopify.dev/docs/apps/launch/deployment/deploy-app-versions)
