Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 55 ยท Storefront API and Headless

Building a Cart with the Storefront API

Build a cart with the Shopify Storefront API: cartCreate, cartLinesAdd, buyer identity, attributes, discount codes and the checkoutUrl, with a runnable in-memory stand-in.

In a custom storefront, the cart is the one piece of state that must live on Shopify's side. The product catalog is something you only read, but the moment a shopper clicks "Add to bag", you need a durable object that holds the lines, applies discounts, knows the buyer's country, and can hand the shopper to a checkout that Shopify hosts. The Storefront API's cart is that object.

This lesson walks through the cart mutations in the order you will use them: create, add, update, remove, attach buyer details, attributes and discount codes, then redirect to checkoutUrl. The real calls are read-only blocks (they need a shop and token, see Storefront API Basics), and a runnable in-memory cart shows the same rules, including how mutations report problems. All requests target Storefront API version 2026-07. For the general design theory of carts, read Cart Design.

Creating a cart

cartCreate takes an optional CartInput and returns the new cart. You can create an empty cart, or include the first lines at once. Store the returned id (a global ID like gid://shopify/Cart/...) wherever your storefront keeps session state, usually a cookie, so you can find the cart again on the next request.

GRAPHQL
# read-only
mutation CreateCart($lines: [CartLineInput!]) {
  cartCreate(input: { lines: $lines }) {
    cart {
      id
      checkoutUrl
      totalQuantity
      cost { totalAmount { amount currencyCode } }
    }
    userErrors { field message code }
  }
}

Variables:

JSON
{ "lines": [{ "merchandiseId": "gid://shopify/ProductVariant/1001", "quantity": 2 }] }

Two details matter. First, lines refer to a variant, not a product: merchandiseId is a ProductVariant ID, because the variant is the thing that has a price and stock (Variants and Options). Second, as with Admin mutations, failures arrive in userErrors, so a 200 OK response does not mean the line was added. Check it every time, as in Mutations and userErrors.

Changing the cart

Once you have an ID, use the dedicated mutations:

Goal Mutation Key arguments
Add lines cartLinesAdd cartId, lines: [{ merchandiseId, quantity }]
Change a quantity cartLinesUpdate cartId, lines: [{ id, quantity }] (the line id)
Remove lines cartLinesRemove cartId, lineIds
Custom data cartAttributesUpdate cartId, attributes: [{ key, value }]
Order note cartNoteUpdate cartId, note
Buyer details cartBuyerIdentityUpdate cartId, buyerIdentity
Discount codes cartDiscountCodesUpdate cartId, discountCodes
GRAPHQL
# read-only
mutation AddLine($cartId: ID!, $lines: [CartLineInput!]!) {
  cartLinesAdd(cartId: $cartId, lines: $lines) {
    cart {
      id
      totalQuantity
      lines(first: 50) { nodes { id quantity merchandise { ... on ProductVariant { title } } } }
    }
    userErrors { field message code }
  }
}

Note the difference between the two ID types. cartLinesAdd takes a variant ID (merchandiseId), while cartLinesUpdate and cartLinesRemove take the cart line ID, which Shopify creates. Mixing them up is the most common bug here. Adding a variant that is already in the cart increases the quantity of the existing line rather than creating a duplicate line, which is how most storefronts expect it to behave, but check the line list in the response instead of assuming.

Attributes

Line-level and cart-level attributes are free key/value pairs that travel with the cart into the order. They are how you pass personalization ("engraving: Maya") or tracking data. cartLinesAdd accepts attributes on each line, and cartAttributesUpdate sets cart-level ones. Updating cart attributes replaces the list you send, so include the existing pairs you want to keep.

Buyer identity

buyerIdentity tells Shopify who the cart is for and where. It can hold an email, a phone, a countryCode, and a customer access token for a signed-in customer. The country matters most: prices, taxes and shipping availability depend on the market (Currencies and Localization). If a shopper changes their country selector, update the cart with cartBuyerIdentityUpdate; do not just change what you display.

GRAPHQL
# read-only
mutation SetBuyer($cartId: ID!) {
  cartBuyerIdentityUpdate(
    cartId: $cartId
    buyerIdentity: { email: "[email protected]", countryCode: DE }
  ) {
    cart { id buyerIdentity { email countryCode } }
    userErrors { field message code }
  }
}

Attaching a buyer email or customer token lets checkout prefill details and tie the order to the customer. Treat this as personal data: see Privacy and Compliance.

Discount codes

cartDiscountCodesUpdate takes the full list of codes the shopper has entered. Sending a new list replaces the old one, so to add a code you send the previous codes plus the new one, and to remove all codes you send an empty list. After the call, read cart.discountCodes { code applicable }: applicable: false means the code was recorded but does not apply (not valid for this cart, expired, or requirements not met). The pricing rules behind that are in Promotions Engine.

GRAPHQL
# read-only
mutation Codes($cartId: ID!, $codes: [String!]) {
  cartDiscountCodesUpdate(cartId: $cartId, discountCodes: $codes) {
    cart {
      discountCodes { code applicable }
      cost { subtotalAmount { amount } totalAmount { amount } }
    }
    userErrors { field message }
  }
}

Sending the shopper to checkout

The cart's checkoutUrl is a link to Shopify's hosted checkout for exactly that cart. Your storefront redirects the shopper there; payments, shipping rates, taxes and the order itself are handled by Shopify. This is a big benefit of headless on Shopify: you design every page except the one with the highest security burden (PCI and 3-D Secure). Treat the URL as short-lived: re-read the cart for a fresh checkoutUrl when the shopper clicks the checkout button rather than caching it.

An in-memory cart stand-in

The stand-in below follows the same rules as the API: lines belong to variants, repeated adds merge, updates use line IDs, a missing cart or an invalid quantity returns userErrors rather than throwing, and discount codes are replaced as a whole. The prices and codes are made up, and money is kept in integer cents as recommended in Money as Integers.

JS An in-memory cart with userErrors

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

No output.

A second view of the same idea is a single "lines to variables" helper, because the Storefront mutations all want their lines in a certain shape. This one turns a plain list from your UI into the variables for cartLinesAdd, merging duplicates before they are ever sent.

JS Build cartLinesAdd variables from UI input

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

No output.

sequenceDiagram
    participant U as Shopper
    participant S as Your storefront
    participant API as Storefront API
    U->>S: Add to bag
    S->>API: cartCreate / cartLinesAdd
    API-->>S: cart, userErrors
    U->>S: Enter code, choose country
    S->>API: cartDiscountCodesUpdate / cartBuyerIdentityUpdate
    U->>S: Checkout
    S-->>U: Redirect to checkoutUrl

Your storefront owns the pages; Shopify owns the cart data and the checkout.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which ID does cartLinesAdd need for each line?

    A variant is what has a price and stock, so lines are added by merchandiseId (a ProductVariant id). Updating or removing later uses the cart line id Shopify created.
  2. 2. A cartLinesAdd response has HTTP 200 and a userErrors entry. What happened?

    GraphQL mutations report business-rule failures in userErrors while still returning 200. Always check it before assuming success.
  3. 3. You call cartDiscountCodesUpdate with ["B"] when the cart had ["A"]. What are the codes afterwards?

    The mutation replaces the list. To keep A and add B, send both codes.
  4. 4. Why should you re-read the cart for checkoutUrl when the shopper clicks Checkout?

    Treat checkoutUrl as a fresh, short-lived link to the cart as it is now rather than a value to cache for days.

Summary

  • A cart is created with cartCreate, found again by its global ID, and changed with dedicated mutations.
  • Lines are added by variant ID (merchandiseId) and updated or removed by cart line ID.
  • Attributes, buyer identity (including country) and discount codes are set with their own mutations; codes and attributes are replaced as a whole.
  • Always check userErrors and discountCodes.applicable, then redirect to a fresh checkoutUrl.

Next: Headless Commerce and Hydrogen.