Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 61 ยท JavaScript, CSS and Design

The Section Rendering API and Dynamic Updates

Use the Shopify Section Rendering API to fetch fresh section HTML, swap it into the page and update variants, carts and filters without a full reload.

Liquid runs on Shopify's servers, so JavaScript in the browser cannot call {{ product.price | money }} itself. That is a problem the moment a page has to change without a reload: a new variant is selected, an item is added to the cart, a filter is applied. You could rewrite every price, label and image in JavaScript, but then your markup lives in two places (Liquid and JS) and the two drift apart.

The Section Rendering API solves this. You ask Shopify to render one or more sections for you and send back the HTML. Your script then swaps that HTML into the page. Liquid stays the single source of truth for markup, and JavaScript only moves the result around. This lesson explains the request formats, how to replace HTML safely, and the pitfalls (stale responses, focus, caching). It builds on Sections and Variants and Option Pickers, and the cart lessons use it heavily.

The Section Rendering API belongs to Shopify's storefront, so the Liquid and fetch snippets here are read-only and describe the behavior of current Online Store 2.0 themes. The live examples use a small fake server written in JavaScript that mimics the request shapes, so you can watch the logic run. Shopify can change limits; check the current reference before relying on a number such as the maximum sections per request.

Two ways to ask for a section

The API works on any storefront URL. You do not call a special endpoint; you add a query parameter to a normal page URL.

1. The sections parameter returns JSON with one entry per requested section:

JavaScript
const response = await fetch('/?sections=header,cart-drawer');
const data = await response.json();
// { "header": "<div id=\"shopify-section-header\" ...>...</div>",
//   "cart-drawer": "<div id=\"shopify-section-cart-drawer\" ...>...</div>" }

Pass several section ids separated by commas. Shopify limits how many you can request at once (at the time of writing, five), so ask for what you need and no more. The key in the JSON is the section id; the value is that section's HTML, wrapped in its shopify-section-<id> element.

2. The section_id parameter returns one section as plain HTML (not JSON):

JavaScript
const url = `${window.location.pathname}?variant=${variantId}&section_id=${sectionId}`;
const html = await fetch(url).then((r) => r.text());

The path matters. The section is rendered in the context of the page you request, so /products/stoneware-mug?variant=101&section_id=main-product renders the product section with that variant selected, exactly as a normal page load would. Request / instead and the product object is not there.

Finding the right section id

The id you pass is the id of the section instance, not the file name. For a static section placed in a JSON template, the id looks like template--12345678__main. For a section in a header or footer group it looks like sections--12345678__header. Do not hard-code these. Read the id from the DOM, where Shopify wraps every section in id="shopify-section-<id>", or print section.id from Liquid into a data-section-id attribute:

LIQUID
<div class="product" data-section-id="{{ section.id }}">
  ...
</div>

Then the script reads element.dataset.sectionId and never needs to know the long generated names. See Building a Section for what section.id contains.

The cart endpoints can render sections too

When the Ajax Cart API changes the cart, you usually also need the updated cart UI. Instead of a second request, add sections (and optionally sections_url) to the body of the cart request:

JavaScript
const response = await fetch('/cart/add.js', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    items: [{ id: 101, quantity: 1 }],
    sections: 'cart-drawer,cart-icon-bubble',
    sections_url: window.location.pathname,
  }),
});
const result = await response.json();
// result.sections['cart-drawer'] is fresh HTML reflecting the new cart

The response now contains the normal cart data plus a sections object. One round trip adds the item and returns the updated drawer. This is the technique behind Building a Cart Drawer.

Replacing HTML safely

You have a string of HTML. How do you put it on the page?

The blunt way is element.innerHTML = html. It works, but it destroys everything inside: scroll positions, focus, text a user is typing, open <details> elements, running animations and any web components that were already set up. For a small price label that is fine. For a whole product section it is not.

A better pattern has three steps:

  1. Parse the response into a detached document with new DOMParser().parseFromString(html, 'text/html').
  2. Select only the pieces you want from it, such as .price, .product-form__buttons or .cart-items.
  3. Replace those pieces in the live page and leave the rest alone.
JavaScript
const incoming = new DOMParser().parseFromString(html, 'text/html');

for (const selector of ['.price', '.product-form__buttons', '.product__sku']) {
  const fresh = incoming.querySelector(selector);
  const current = document.querySelector(`[data-section-id="${sectionId}"] ${selector}`);
  if (fresh && current) current.replaceWith(fresh);
}

Replacing small, named regions keeps the gallery from flickering and the quantity box from losing its value. Some themes go further and use a morphing library (Idiomorph is a popular one): it compares the old and new DOM trees and changes only what differs, keeping the elements the user is interacting with. Morphing is convenient, but it is a dependency to load, so decide whether a handful of replaceWith calls is enough.

HTML returned by the API is your own store's markup, rendered by Liquid, so it is as trustworthy as your theme. Never feed it with text from another origin or from user input and then insert it with innerHTML. See Security in Themes.

sequenceDiagram
  participant S as Shopper
  participant J as Theme JS
  participant R as Shopify (Liquid)
  S->>J: picks a new variant
  J->>R: GET /products/mug?variant=103&section_id=main-product
  R-->>J: HTML of the section for variant 103
  J->>J: parse, pick .price and .buttons
  J->>S: swap in the new pieces, keep focus

The browser asks for markup instead of building it. Liquid renders it, and JS only swaps the parts that changed.

Variant changes without a reload

Put the pieces together for a variant picker:

  1. The shopper selects a new option value.
  2. JavaScript finds the matching variant (see the lookup in Variants and Option Pickers).
  3. It updates the hidden id input and the URL with history.replaceState.
  4. It requests ?variant=<id>&section_id=<section> for the current product path.
  5. It swaps the price, buttons, SKU and gallery pieces.

The benefit shows when your Liquid does something non-trivial: showing a "Save 20%" badge, a low-stock message, a metafield, a translated sold-out label. The server already knows how, so you do not rebuild that logic in JavaScript.

Race conditions: only the latest answer wins

Networks are not ordered. If a shopper clicks Blue, then Green quickly, the Green response could arrive before the Blue response. If you apply responses as they come in, the page ends up showing Blue's price next to the Green selection. The fix is to give every request a number, or to abort the old request with an AbortController, and ignore any response that is not the latest. The second live example below demonstrates this.

Caching and cost

Each Section Rendering call runs Liquid on the server, so it is cheaper than a full page load but not free. Keep these ideas in mind:

  • Ask for as few sections as you can. A request for the whole product section when only the price changed does a lot of unnecessary rendering. Splitting a section into smaller sections only for the API's sake is rarely worth it; instead choose which pieces you use from the response.
  • Cache on the client. A Map keyed by URL lets the second click on a variant be instant. Be careful with anything depending on the cart: a cached cart drawer is wrong after the next add.
  • Do not assume shared caching. Responses can differ by cart, customer, market and language. Treat them as private to the visitor unless you have verified otherwise, and never hard-code assumptions about CDN behavior.
  • Debounce rapid input. For price sliders and filters, wait a short moment after the last change before sending the request.
  • Handle failure. A failed fetch should leave the old content in place and show a short message, not a blank section.

Stand-in: a fake server that understands the parameters

Below is a tiny "server" that renders sections from a template and answers in the same two formats as the real API. It is a stand-in: the real renderer is Liquid on Shopify's servers, here it is a plain function. What is real is the shape of the requests and responses.

JS Stand-in: sections and section_id

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

No output.

Stand-in: swapping pieces and ignoring stale answers

The second example performs a variant change the careful way: it parses the response, replaces only the price and button region, caches by URL, and drops answers that arrive out of order. The "server" answers the first click slowly and the second quickly, to force the race.

JS Stand-in: variant change with a stale-response guard

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

No output.

If you remove the ticket !== latest check, the slow answer for variant 101 would overwrite the correct 103 price. That bug is easy to miss on a fast connection and obvious on a phone.

Accessibility and focus

Swapping HTML can steal the user's place. Keep these habits:

  • Do not replace the element that currently has focus; replace its siblings, or restore focus afterward.
  • Announce meaningful changes with an aria-live="polite" region ("Added to cart", "Price updated"). More in Accessibility in Themes.
  • Keep the Back button predictable: use replaceState for variant changes and pushState only when the view really is a new page (filters, for example).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the section_id query parameter return?

    section_id returns one section as plain HTML. It is rendered for the URL you request, so the product page path is needed for the product object to exist.
  2. 2. Why do cart requests accept a sections parameter?

    Adding sections to /cart/add.js (and friends) returns fresh HTML for those sections along with the cart data, so the drawer can update without a second request.
  3. 3. A shopper clicks two variants quickly and sees the wrong price. What is the most likely cause?

    Responses can arrive out of order. Number requests or abort the old one, and ignore any response that is not for the latest request.
  4. 4. Why is replacing only selected pieces usually better than setting innerHTML on the whole section?

    Replacing the whole section throws away state in elements the shopper may be using. Swapping small named regions leaves everything else untouched.

Summary

  • The Section Rendering API returns Liquid-rendered HTML for any storefront URL: ?sections=a,b for JSON, ?section_id=x for one section as HTML.
  • Request the URL of the page whose context you need (for example the product page with ?variant=).
  • Cart endpoints can return sections too, which saves a round trip.
  • Parse the response, swap only the pieces that changed, and keep focus and state intact; morphing libraries automate this.
  • Guard against stale responses, cache carefully, and never assume a response is shareable between visitors.

Next, make your theme work in many languages and currencies in Translations, Markets and Localization.