Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 61 ยท Projects

Project: A Product Bundle Builder

Build a Shopify bundle builder: a section with product blocks, a multi-select UI, one Ajax call that adds many lines, line item properties and an honest discount note.

A bundle builder lets shoppers pick several products, such as a mug, a tea towel and a planter, and add them to the cart together. Merchants like it because it raises the order value; shoppers like it because it is one decision instead of three. For a theme developer it is a good exercise, because it touches four things you have already met: a section with blocks, a small piece of state in JavaScript, the Ajax cart API with several items in a single request, and line item properties.

You will build it in layers. First the section and its schema, so a merchant chooses the products in the theme editor. Then the selection logic. Then the single /cart/add.js call that adds every chosen line at once. Finally the discount note, and an honest talk about what a theme can and cannot do about prices. The theme code is read-only, because Liquid and the cart exist only on Shopify. Beside it are runnable stand-ins in JavaScript with a fake cart server, so you can test the rules. You should know sections, blocks, the product form and the Ajax cart API.

The Liquid and schema in this lesson target current Online Store 2.0 themes. The stand-ins use made-up products and an in-memory fake server: nothing contacts Shopify.

What the finished feature does

The shopper sees a heading, a row of product tiles (each with an image, title, price and a checkbox) and a summary bar. Choosing a tile adds it to the pending bundle. The bar shows the count, the subtotal and a note such as "Add 1 more to unlock the bundle offer". The button sends all chosen variants to the cart in one request.

flowchart LR
  A["Merchant picks products<br/>in the theme editor"] --> B["Section renders<br/>one tile per block"]
  B --> C["Shopper ticks tiles<br/>(pending bundle in JS)"]
  C --> D["One POST to<br/>/cart/add.js with items"]
  D --> E["Cart lines share a<br/>bundle id property"]

Data flows from the editor, through the section markup and a little state, into a single cart request.

The section: one block per product

Each product tile is a block of the section, so the merchant adds, removes and reorders them in the editor, and chooses each product with a product picker setting. Put the file at sections/bundle-builder.liquid:

LIQUID
{%- comment -%} sections/bundle-builder.liquid {%- endcomment -%}
<bundle-builder
  class="bundle"
  data-min="{{ section.settings.min_items }}"
  data-cart-url="{{ routes.cart_add_url }}.js"
  {{ section.shopify_attributes }}
>
  <h2>{{ section.settings.heading | escape }}</h2>

  <ul class="bundle__grid">
    {%- for block in section.blocks -%}
      {%- assign item = block.settings.product -%}
      {%- if item != blank and item.available -%}
        {%- assign variant = item.selected_or_first_available_variant -%}
        <li class="bundle__tile" {{ block.shopify_attributes }}>
          <label>
            <input
              type="checkbox"
              name="bundle_item"
              value="{{ variant.id }}"
              data-price="{{ variant.price }}"
              {% unless item.has_only_default_variant %}disabled{% endunless %}
            >
            {{ item.featured_image | image_url: width: 300 | image_tag: alt: item.title, loading: 'lazy' }}
            <span class="bundle__title">{{ item.title | escape }}</span>
            <span class="bundle__price">{{ variant.price | money }}</span>
          </label>
        </li>
      {%- endif -%}
    {%- endfor -%}
  </ul>

  <p class="bundle__note" role="status"></p>
  <button type="button" class="bundle__add" disabled>Add bundle to cart</button>
</bundle-builder>

{% schema %}
{
  "name": "Bundle builder",
  "tag": "section",
  "max_blocks": 8,
  "settings": [
    { "type": "text", "id": "heading", "label": "Heading", "default": "Build your bundle" },
    { "type": "range", "id": "min_items", "label": "Items needed for the offer", "min": 2, "max": 5, "step": 1, "default": 3 }
  ],
  "blocks": [
    {
      "type": "product",
      "name": "Product",
      "settings": [
        { "type": "product", "id": "product", "label": "Product" }
      ]
    }
  ],
  "presets": [{ "name": "Bundle builder" }]
}
{% endschema %}

Several choices here are deliberate.

  • Only single-variant products are selectable. The tile uses selected_or_first_available_variant, so a product with sizes would silently add the first size. The unless item.has_only_default_variant line disables those tiles in this basic version. A production bundle with sizes adds a small option picker per tile, as in the variants lesson.
  • Unavailable or empty blocks are skipped. A block whose picker is still empty (blank) or whose product is sold out never renders a tile.
  • routes.cart_add_url comes from the routes object, so the URL keeps working under a language or market prefix.
  • block.shopify_attributes lets the theme editor select a tile when the merchant clicks it.
  • max_blocks keeps the grid a size the page and the request can handle.

The tile also needs a visible focus style and a real label, which the wrapping <label> provides. The role="status" paragraph is a polite live region, so a screen reader hears "2 items selected" without focus moving.

Selection state and the rules

Keep the pending bundle in one small object, and keep the rules (how many are needed, what the note says) in plain functions that do not touch the page. Pure functions are easy to test, which is exactly what the first stand-in does.

JS Stand-in: bundle rules and the note text

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

No output.

The sold-out spoon is ignored even when its id sneaks into the selection: the rule filters on available, the same condition the Liquid used when it rendered the tile. Never trust only the markup; a stale tab can hold ids that have since sold out.

One request, many lines

The Ajax cart API accepts an items array, so the whole bundle goes in a single POST to /cart/add.js. That matters for two reasons. It is one round trip instead of three. And it is all or nothing: if one line cannot be added (say it is out of stock), the request fails with a 422 and no line is added, so the cart never ends up with half a bundle.

Give every line the same line item property so the lines can be recognized as one bundle later:

JavaScript
// Real browser code for the bundle button (read-only here).
class BundleBuilder extends HTMLElement {
  connectedCallback() {
    this.button = this.querySelector('.bundle__add');
    this.note = this.querySelector('.bundle__note');
    this.addEventListener('change', () => this.update());
    this.button.addEventListener('click', () => this.addToCart());
  }

  get selected() {
    return [...this.querySelectorAll('input[name="bundle_item"]:checked')];
  }

  update() {
    const count = this.selected.length;
    const min = Number(this.dataset.min);
    this.button.disabled = count === 0;
    this.note.textContent = count >= min
      ? 'Bundle offer unlocked.'
      : 'Add ' + (min - count) + ' more to unlock the bundle offer.';
  }

  async addToCart() {
    const bundleId = 'bundle-' + Date.now();
    const items = this.selected.map(input => ({
      id: Number(input.value),
      quantity: 1,
      properties: { _bundle: bundleId }
    }));

    this.button.disabled = true;
    try {
      const response = await fetch(this.dataset.cartUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({ items })
      });
      const data = await response.json();
      if (!response.ok) throw new Error(data.description || data.message);
      this.note.textContent = items.length + ' items added to your cart.';
      document.dispatchEvent(new CustomEvent('cart:updated'));
    } catch (error) {
      this.note.textContent = error.message;
    } finally {
      this.button.disabled = this.selected.length === 0;
    }
  }
}
customElements.define('bundle-builder', BundleBuilder);

Notes on this code:

  • The property name starts with an underscore. By convention, themes hide line item properties whose names begin with _ from the cart display. Shopify does not enforce this in your theme, so your cart snippet must do it: skip properties where property.first starts with _. Do not put anything secret in a property, because shoppers can edit them in the browser.
  • The bundle id is made on the client. That is fine for grouping lines. It is not proof of anything: a shopper could send the same property without buying a bundle, which is why it must never decide a price (see below).
  • The button is locked while the request runs and its state is recomputed in finally, the same pattern as in the product card project.
  • Errors are shown in the live region. The server's description is already written for humans.

Now run the same logic against a fake server that enforces stock and the all-or-nothing rule.

JS Stand-in: add the whole bundle in one fake request

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

No output.

Look at the second request: variant 101 was fine, but because 103 failed, the cart still has three lines. That is the behavior to rely on when you describe the feature to a merchant ("the bundle is added completely or not at all").

The discount note, and what a theme cannot do

It is tempting to make the builder "give 10% off". A theme cannot. Prices and discounts are decided by Shopify's checkout, using discount codes, automatic discounts or Shopify Functions, not by JavaScript on the product page. Anything your script displays is a note, not a price. If the note and the real checkout disagree, the shopper loses trust, and a shopper who edits the page can see any number they like.

A safe design splits the work:

  1. The merchant creates an automatic discount that applies when the cart contains a set quantity of the eligible products (or uses an app or a Function for a rule like "any 3 from this collection").
  2. The theme shows a note that matches that rule, with the threshold taken from a section setting so it can be kept in step.
  3. The cart page and drawer show the discount Shopify actually applied, using the line and cart discount data covered in Cart, Discounts and the Path to Checkout.

For the price-rule thinking behind this (stacking, thresholds, rounding, why the server must be the source of truth), see the e-commerce lesson on promotions and price rules instead of repeating them here.

Never compute the final price in the theme and send it to the cart. The cart endpoints take variant ids and quantities; they ignore a price field, and checkout recomputes everything on the server.

Extending the project

Ideas to try once the basic version works: a per-tile quantity stepper (quantities above 1 need the stock check to use the sum); a variant picker per tile; a progress bar that fills as items are chosen; a "remove the whole bundle" button in the cart that uses /cart/update.js with every line key sharing the _bundle value set to 0; and keyboard testing of the whole flow with only Tab and Space.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the bundle builder send all items in one request to /cart/add.js?

    The items array is validated as a whole. A 422 for one line means no line is added, which keeps the bundle consistent.
  2. 2. What is the purpose of a line item property such as _bundle?

    Properties are free-form data stored on the line. Themes conventionally hide names that start with an underscore, but the shopper can still alter them, so they never decide prices.
  3. 3. Which statement about a bundle discount is correct?

    Pricing belongs to the server. The cart ignores client-supplied prices, so the theme can only describe an offer that a discount rule really implements.
  4. 4. Why does the section skip blocks whose product is blank or unavailable?

    A freshly added block has no product yet, and offering a sold-out item makes the all-or-nothing request fail. Filtering in Liquid avoids both.
  5. 5. Why is the note paragraph given role="status"?

    A status region is a polite live region: updates such as how many items are still needed are spoken without interrupting the shopper.

Summary

  • Model each bundle product as a section block with a product picker, and skip blank or unavailable blocks in Liquid.
  • Keep the selection rules in pure functions, and recompute availability instead of trusting stale markup.
  • Add every chosen variant with one POST to /cart/add.js using items; one failing line fails the whole request.
  • Tag the lines with a shared underscore-prefixed property to group them, and remember that properties are shopper-editable.
  • A theme can only display a discount note; real discounts come from Shopify discounts or Functions and are verified at checkout.

Next, test what you have learned in Practice Exercises with Solutions.