Skip to content
Tutorials Center
My learning

Topics

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

Building a Cart Drawer

Build a Shopify cart drawer: refresh it with the Section Rendering API, update quantities optimistically, manage focus for accessibility, and add a shipping bar.

A cart drawer is the panel that slides in after a shopper adds something, so they never leave the product page. It looks like a small feature, but it combines almost everything you have learned so far: a Liquid section that renders the cart, Ajax requests that change it, HTML that is swapped in without a reload, and keyboard and screen-reader behavior that has to be right. A drawer that traps focus badly or never announces changes is worse than a plain cart page.

This lesson builds on The Product Form and Add to Cart and The Ajax Cart API. You will see the real theme code (read-only, because Liquid and the cart endpoints exist only on Shopify) and run honest stand-ins: a fake cart server written in JavaScript, and a working drawer in the browser that follows the same structure a real theme uses.

The cart endpoints and the sections parameter described here are part of Shopify's storefront Ajax APIs as of the current 2.0+ theme platform. Endpoint behavior and available fields do evolve, so check the current reference before shipping. The live examples never contact Shopify.

The parts of a drawer

A drawer has four moving parts, and keeping them separate makes the code easier to reason about:

  1. A section (for example sections/cart-drawer.liquid) that renders the cart contents as HTML. It is the single source of truth for markup.
  2. A custom element (see JavaScript in Themes) that opens and closes the panel and handles clicks.
  3. Ajax calls to /cart/add.js, /cart/change.js and /cart/update.js that change the cart.
  4. A refresh step that replaces the drawer HTML after every change.
sequenceDiagram
  participant S as Shopper
  participant D as Drawer script
  participant API as Shopify cart API
  S->>D: Click "+" on a line
  D->>D: Optimistic update (show 3 right away)
  D->>API: POST /cart/change.js (line, quantity, sections)
  API-->>D: Cart JSON + rendered section HTML
  D->>D: Replace drawer HTML, restore focus

The request asks for the new cart and the freshly rendered drawer in a single round trip.

Rendering the cart in Liquid

The section is ordinary Liquid. It loops over cart.items, prints each line, and shows totals. Keep every dynamic piece inside it so the server decides what the drawer looks like:

LIQUID
<cart-drawer id="CartDrawer" class="cart-drawer">
  <div class="cart-drawer__panel" role="dialog" aria-modal="true" aria-labelledby="CartDrawerTitle" hidden>
    <h2 id="CartDrawerTitle">Your cart ({{ cart.item_count }})</h2>

    {%- if cart.item_count == 0 -%}
      <p>Your cart is empty.</p>
    {%- else -%}
      <ul>
        {%- for item in cart.items -%}
          <li data-line="{{ forloop.index }}" data-key="{{ item.key }}">
            <a href="{{ item.url }}">{{ item.product.title }}</a>
            <span>{{ item.variant.title }}</span>
            <input type="number" min="0" value="{{ item.quantity }}"
                   aria-label="Quantity for {{ item.product.title }}">
            <span>{{ item.final_line_price | money }}</span>
          </li>
        {%- endfor -%}
      </ul>
      <p>Subtotal: {{ cart.total_price | money }}</p>
      <a href="{{ routes.cart_url }}">View cart</a>
      <button type="submit" form="CartForm" name="checkout">Check out</button>
    {%- endif -%}
  </div>
</cart-drawer>

{% schema %}
{ "name": "Cart drawer", "settings": [] }
{% endschema %}

Two details matter. item.key is a stable identifier for a line (variant id plus properties), and forloop.index is the 1-based line number that /cart/change.js accepts as line. Prefer the key or id when your code can, because a line number shifts when another line disappears.

Refreshing with the Section Rendering API

After a change you need the new HTML, not just new numbers. Re-rendering the drawer in JavaScript would duplicate your Liquid. Instead, ask Shopify to render the section for you by adding a sections parameter to the cart request:

JavaScript
const response = await fetch(window.Shopify.routes.root + 'cart/change.js', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
  body: JSON.stringify({
    line: 2,
    quantity: 3,
    sections: 'cart-drawer,cart-icon-bubble',
    sections_url: window.location.pathname,
  }),
});
const data = await response.json();
// data.sections['cart-drawer'] is a string of HTML

The response contains the usual cart JSON plus a sections object whose keys are the section ids you asked for. You parse the HTML string, pick the part you need and swap it in:

JavaScript
const html = new DOMParser().parseFromString(data.sections['cart-drawer'], 'text/html');
const fresh = html.querySelector('#CartDrawer .cart-drawer__panel');
document.querySelector('#CartDrawer .cart-drawer__panel').replaceWith(fresh);

The section ids you request must match the section file names (cart-drawer) or the ids of sections placed in a section group. The deeper mechanics, including ?section_id= on a normal page URL, are covered in The Section Rendering API.

Optimistic UI

A round trip takes tens or hundreds of milliseconds. If the number only changes after the response arrives, the drawer feels sluggish. Optimistic UI means you show the expected result immediately and fix it if the server disagrees:

  1. remember the previous quantity;
  2. update the number on screen;
  3. send the request;
  4. on success, replace the HTML with the server's version (which is the truth);
  5. on failure (for example, not enough stock), restore the old value and show the error message.

The server stays authoritative: the optimistic number is a guess, and step 4 always overwrites it. Never compute prices on the client and trust them. Money values come back from the server, and for the reasons in Money as Integers they arrive in the smallest currency unit.

Also guard against overlapping requests. If the shopper taps "+" three times quickly, three requests race. A simple rule is to queue them or disable the controls of that line until the response comes back.

Stand-in: a fake cart server and an optimistic update

This first stand-in is plain JavaScript. A tiny object plays the role of Shopify (stock limits, line prices, a rejected request), and the update function follows the five steps above. The real thing is the same flow with fetch instead of a local function.

JS Stand-in: optimistic update with rollback

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

No output.

The first change succeeds and the second is rejected, so the screen ends with 4, 1. In a real theme the rejected response is a 422 with a message you can show next to the line.

Accessibility and focus management

A drawer is a dialog, and dialogs have rules:

  • Move focus in when it opens, usually to the close button or the heading.
  • Keep focus inside while it is open. The native <dialog> element opened with showModal() does this for you, and also makes the rest of the page inert. If you build the panel from a div with role="dialog" and aria-modal="true", you must trap focus yourself.
  • Close with Escape and return focus to the element that opened it (the cart icon or the add-to-cart button).
  • Announce changes. Put an aria-live="polite" region in the drawer and write short messages such as "Quantity updated to 3" or "Item removed". Without this, screen reader users get no feedback after pressing "+".
  • Restore focus after a refresh. When you replace the HTML, the element the shopper just used no longer exists. Remember its data-key and the action, then focus the equivalent new element.

More on this is in Accessibility in Themes.

Free shipping bar, notes and discount codes

The free shipping bar is a progress message based on cart.total_price and a threshold from a section setting. Compute it in Liquid so the first paint is right, and recompute it from the refreshed HTML afterward:

LIQUID
{%- assign threshold = section.settings.free_shipping_threshold | times: 100 -%}
{%- assign remaining = threshold | minus: cart.total_price -%}
{%- if remaining > 0 -%}
  Spend {{ remaining | money }} more for free shipping.
{%- else -%}
  You get free shipping!
{%- endif -%}

The setting is entered in whole currency units, so times: 100 converts it to the cents that cart.total_price uses. This is a message only. Whether shipping is actually free is decided by the store's shipping rates (see Shipping Rates), so make sure the number in your setting matches the real rate.

A cart note is a free-text field saved on the cart. Send it with /cart/update.js:

JavaScript
await fetch(window.Shopify.routes.root + 'cart/update.js', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ note: 'Please include a gift receipt' }),
});

Debounce this call (wait for a pause in typing) rather than sending it on every keystroke. Discount codes are normally entered at checkout. Some themes accept a code in the cart; the supported approaches have changed over time, so read the current Ajax API reference and show the real result from the server rather than guessing a discount yourself. For how discounts combine, see Building a Promotions Engine.

Stand-in: a working drawer

The second stand-in is a drawer in the browser. It uses a native <dialog>, a fake cart, a free shipping bar, an aria-live message and focus restore. It follows the real structure, but the data lives in a script and nothing is sent anywhere.

Stand-in: cart drawer with focus management

Open the drawer, press + until the bar fills, then press Escape. Focus returns to the button that opened it. After each press, the buttons are re-created by render, so the code focuses the equivalent button again. That is the same job your theme performs after swapping in server-rendered HTML.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why ask for the drawer HTML with the sections parameter instead of building it in JavaScript?

    The response carries the new cart plus the rendered section, so you do not duplicate your Liquid in JavaScript and you need only one round trip.
  2. 2. A shopper presses + but the item has no more stock. What should an optimistic UI do?

    The optimistic number was only a guess. When the server rejects it, restore the old value and explain why.
  3. 3. Which behavior is part of good drawer accessibility?

    Focus moves into the dialog on open, stays there while it is open, and returns to the opener on close. Changes are announced through an aria-live region.
  4. 4. The free shipping threshold setting is entered as 50. Why does the Liquid multiply it by 100?

    Shopify money values are integers in the smallest unit, so the whole-unit setting must be converted before comparing.

Summary

  • A drawer is a Liquid section plus a custom element, Ajax cart calls and an HTML refresh.
  • Add sections to cart requests to receive freshly rendered HTML together with the new cart.
  • Optimistic UI shows the expected result at once, then lets the server's response overwrite it or triggers a rollback.
  • Treat the drawer as a dialog: move focus in, trap it, close on Escape, return focus, and announce changes with aria-live.
  • The shipping bar is a message computed from integer cents; real shipping rules live in the store settings.

Next, look at what the cart object contains and where the theme's control ends in Cart, Discounts and the Path to Checkout.