Merx

Showing the cart

Learn how to show the customer’s cart using JavaScript.

We recommend using JavaScript and the API to show the cart to the customer. This makes it possible to cache all pages server-side and load the cart asynchronously.

Let’s define a custom element for it. It has a fetchCart() function, which gets the cart data from the API endpoint, and a render() function, which renders the cart as a list.

script.js
customElements.define('my-cart', class extends HTMLElement {
  /** @see https://merx.wagnerwagner.de/reference/api/models/cart */
  data = null;

  endpoint = '/api/shop/cart';

  async fetchCart() {
    const response = await fetch(this.endpoint, {
      headers: {
        'X-Language': document.documentElement.lang,
      },
    });
    const json = await response.json();
    this.data = json.data;
  }

  async connectedCallback() {
    await this.fetchCart();
    this.render();
  }

  render() {
    const items = this.data?.products?.items ?? [];

    this.innerHTML = `
      <h2>Cart</h2>
      ${items.length === 0 ? '<p>Empty cart</p>' : `
        <ul>
          ${items.map(item => `
            <li>
              <strong>${item.title}</strong><br>
              Price: ${item.price?.price ?? 'On request'}
            </li>
          `).join('')}
        </ul>
        <p>Total: ${this.data.total?.price ?? ''}</p>
        ${this.data.checkout ? `<a href="${this.data.checkout.url}">${this.data.checkout.title}</a>` : ''}
      `}
    `;
  }
});

Add the <my-cart> element to the header of your page — or wherever you want to show the cart.

A product without a price returns null instead of a price object. checkout is null until a page with the checkout template exists, which is the next step, so the link is only rendered once there is one. To check which other fields are available, see the Cart model reference.