Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 61 ยท Cart, Checkout and Customer Pages

The Ajax Cart API

Use the Shopify Ajax Cart API from a theme: cart/add.js, change.js, update.js, clear.js, cart.js, the sections parameter, error handling and rate limits.

The plain product form reloads the page. Shoppers now expect "Add to cart" to update the header count and open a drawer without a refresh. Shopify supports this with the Ajax Cart API: a handful of URLs on the storefront that read and change the current cart and answer with JSON. Your JavaScript calls them with fetch, and the cart stays in the shopper's session cookie, so no tokens or login are involved.

This lesson walks through each endpoint, the request and response shapes, the sections parameter that returns freshly rendered HTML in the same call, error handling and rate limits. It continues The Product Form and Add to Cart and prepares Building a Cart Drawer.

These endpoints exist only on a real store, so the fetch code is read-only and shows the Ajax Cart API as documented for current themes. The runnable examples use a fake server written in JavaScript that follows the same request and response shapes in simplified form. Real responses contain more fields (for example price breakdowns, images and discounts). Check Shopify's reference for the full schema before depending on a field.

The endpoints at a glance

Endpoint Method Purpose
/cart.js GET read the whole cart as JSON
/cart/add.js POST add one or more variants
/cart/change.js POST change one line's quantity (0 removes it)
/cart/update.js POST set many quantities, note and attributes at once
/cart/clear.js POST empty the cart

In a theme, do not hard-code these paths, because stores with language or market sub-paths serve them under a prefix (for example /fr/cart/add.js). Output the URLs from the routes object and add .js:

LIQUID
<cart-api
  data-add="{{ routes.cart_add_url }}.js"
  data-change="{{ routes.cart_change_url }}.js"
  data-update="{{ routes.cart_update_url }}.js"
  data-cart="{{ routes.cart_url }}.js">
</cart-api>

Reading the cart: GET /cart.js

JavaScript
const cart = await fetch('/cart.js').then((response) => response.json());
console.log(cart.item_count, cart.total_price);

The result includes token, note, attributes, item_count, items (an array of lines), total_price and more. Money values are integers in the smallest currency unit (cents), not decimals; format them with your own helper (or Intl.NumberFormat), or ask the server to render HTML. Each line has a key (a unique id for the line), id (the variant id), quantity, properties, title, price and line_price. The same ideas appear in the general model of Cart Design.

Adding: POST /cart/add.js

You can post JSON:

JavaScript
const response = await fetch('/cart/add.js', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
  body: JSON.stringify({
    items: [
      { id: 44001, quantity: 2, properties: { Engraving: 'Ann' } },
      { id: 44005, quantity: 1 },
    ],
  }),
});
const result = await response.json();

or post the product form's own data, which is the least code:

JavaScript
const form = document.querySelector('form[action$="/cart/add"]');
const response = await fetch('/cart/add.js', { method: 'POST', body: new FormData(form) });

Using FormData keeps properties[...] and selling_plan working exactly as in the no-JavaScript case. The response differs by request: adding a single item returns that line item, and an items array returns an object with an items array of the lines added. Adding several lines in one call is much faster than several calls, and it is the base of a bundle builder (see Project: A Product Bundle Builder).

Changing and updating

/cart/change.js changes one line. Identify it with the line key (the safest) or the 1-based line number, and send the new quantity. A quantity of 0 removes the line:

JavaScript
await fetch('/cart/change.js', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ id: line.key, quantity: 3 }),
});

Prefer the key or line over a plain variant id: the same variant can appear on several lines with different properties, and a variant id would be ambiguous. The response is the updated cart.

/cart/update.js changes many things at once: pass updates as an object keyed by variant id (or an array matching line order) and optionally note and attributes:

JavaScript
await fetch('/cart/update.js', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ updates: { 44001: 0 }, note: 'Please gift wrap', attributes: { gift: 'yes' } }),
});

Use it for the cart note and attributes, and for "update cart" buttons. /cart/clear.js simply empties the cart and returns it.

The sections parameter

After a cart change you usually need to redraw something: the count bubble, a drawer, the cart page. The naive way is a second request to fetch HTML. The Ajax Cart API can do it in the same round trip: add sections (a comma-separated list of section ids) and optionally sections_url (the page URL the sections should be rendered for):

JavaScript
body: JSON.stringify({
  id: line.key,
  quantity: 2,
  sections: 'cart-drawer,cart-icon-bubble',
  sections_url: window.location.pathname,
})

The response then contains a sections object with the rendered HTML of each requested section, already reflecting the new cart. You replace the matching elements. This is the Section Rendering API applied to the cart and is covered in depth in The Section Rendering API. The ids refer to sections that exist in your theme's layout or templates, so name them consistently.

sequenceDiagram
  participant J as Theme JS
  participant S as Shopify
  J->>S: POST /cart/change.js (key, quantity, sections)
  S->>S: update cart, render sections
  S-->>J: cart JSON + sections HTML
  J->>J: replace drawer and count bubble

One request updates the cart and returns fresh HTML for the parts of the page that show it.

Errors and rate limits

Check response.ok. A failing call returns an error status with JSON that has a message and a description, and the most common case is 422 when the request is valid in shape but cannot be done, for example adding more than the available stock. The description is a human-readable sentence you can show the shopper in an aria-live region. Do not assume the error text format, and do not parse it for logic.

JavaScript
async function cartRequest(url, payload) {
  const response = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
    body: JSON.stringify(payload),
  });
  const data = await response.json().catch(() => ({}));
  if (!response.ok) {
    const error = new Error(data.description || data.message || `Request failed (${response.status})`);
    error.status = response.status;
    throw error;
  }
  return data;
}

Other cases to design for: 429 Too Many Requests when a script floods the endpoint (a runaway loop, or rapid-fire clicks), and network failures, where fetch itself rejects. Defend against both:

  • disable the button while a request is in flight, so a double click cannot add twice;
  • serialize cart writes through a queue so quantity changes arrive in order, since two parallel changes can overwrite each other;
  • show the error and keep the UI consistent with the server by redrawing from the response.

Rate-limit numbers and behavior are Shopify's to change, so rely on handling the status code and not on a specific threshold.

Stand-in: a fake server and a cart client

This stand-in implements add, change and clear against an in-memory cart, with stock limits that produce a 422-style error. The fakeFetch function mimics the real request and response shapes in simplified form, so you can write the same client code and see success, merge and failure paths.

JS Stand-in: a cart client against a fake server

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

No output.

The failed add leaves the cart unchanged, exactly as you should expect from the real endpoint: the error is data to show, not a reason to guess what the cart looks like.

Stand-in: a request queue and the sections response

Two rules above need code: serialize writes, and redraw from the sections HTML in the response. This stand-in shows both. Three quantity changes fire "at once" but run in order through a promise chain, and the response carries fake rendered HTML that replaces the cart bubble.

JS Stand-in: serialized writes and section redraw

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

No output.

Every write completes in the order it was requested, so the final state is 4, and the page shows what the server last confirmed. Without the queue, the 50 ms request would land last and overwrite the newer values.

Practical rules

  • Send Accept: application/json and handle non-JSON failures (a proxy error page) by catching response.json() errors.
  • Never trust the client total. Redraw prices from the server response, and never calculate what the shopper pays in the theme; discounts and shipping are decided later. See Cart, Discounts and the Path to Checkout.
  • Merge calls where possible: one add.js with several items, one update.js for quantities and note.
  • Announce results in an aria-live region and move focus predictably (see Accessibility in Themes).
  • Safe retries matter in commerce: a retried add can double an item. The general principle is in Idempotency; in a theme, the practical equivalent is to disable the button and ignore repeat clicks.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which endpoint reads the whole current cart as JSON?

    A GET to /cart.js returns the cart, including items, item_count and total_price.
  2. 2. A line should go from 2 to 0 items. What do you send to /cart/change.js?

    Setting the quantity to 0 removes that line. Use the key or line number to identify it unambiguously.
  3. 3. What does the sections parameter do on a cart request?

    The response includes a sections object with fresh HTML, so no second request is needed to redraw the UI.
  4. 4. Adding more units than are in stock normally produces which kind of response?

    The request is well formed but cannot be fulfilled, so an error status and message come back. Check response.ok.
  5. 5. Why serialize cart writes through a queue?

    Parallel changes can finish in a different order than they started. A queue keeps the final state predictable.

Summary

  • The Ajax Cart API is a set of JSON endpoints: cart.js, cart/add.js, change.js, update.js, clear.js; build URLs from routes.
  • Post JSON or FormData; change lines by key or line, and set quantity 0 to remove.
  • Add sections to get rendered HTML back in the same response.
  • Check response.ok, show the error description, handle 422 and 429, and queue writes.
  • Money is in cents and the server is the source of truth for the cart.

Next, assemble these pieces into a working interface in Building a Cart Drawer.