How to Add to the Shopify Cart with Alpine JS

Use Alpine JS to add to the Shopify cart without a page refresh.

This is the approach I take when using Alpine JS with Shopify, is it the easiest? No. However, it provides the most flexibility and ability to scale the frontend of your Shopify store to use more JavaScript.

You can also read the JavaScript approach.

How to Add to the Shopify Cart with Vanilla JS

Let's write some code. I'll assume you have Alpine JS installed.'cart', {
  data: [],

  add() {
    let variant ='variant').selected
    let quantity ='quantity').count

    if (! variant) return

    let cartData = {
      quantity: quantity

    fetch('/cart/add.js', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(cartData),
      .then((response) => {
        if (response.ok) {
          // 🚀
        } else {
          // 🫠
      .catch((error) => {
        // 🫠
}'variant', {
  selected: null,

  set (variant) {
    this.selected = variant
})'quantity', {
  count: 1,

  set (quantity) {
    this.count = quantity

You might be thinking...


And yes, it is quite a lot for what we're doing but remember, this approach offers flexibility.

Let's break it down.

Cart Store

This is the main store, it has two important pieces:

  • Holds the shopify cart data

This can be accessed with $ in HTML and'cart').data` in a JavaScript.

  • Has the add to cart function

There is one thing left out of this example, the function that fetches the Shopify cart data and saves it to the Alpine JS store. That would look like this.

get() {
    .then((response) => response.json())
    .then((data) => ( = data))
    .catch((error) => console.error(error))

Therefore, when the add() function is called we can call'cart').get() to update the store Shopify cart data.

Variant Store

This tracks the currently selected variant.

We can then use the store to get information about the variant from, it can even be used for functionality such as changing images when a variant is selected on the product page.

Quantity Store

This is the one store that could be ignored. However, it offers an easier way to get the chosen quantity from the product form.

Here's some HTML to show how it can be used.

<form x-on:submit.prevent="$store.cart.add()">
    <label for="ProductQty"> Quantity </label>

    <input type="number" id="ProductQty" x-model="$store.quantity.count" />

  <button type="submit"> Add to Cart </button>

If the add() function doesn't get called you can add the following.

  function addToCart() {'cart').add()

And then call addToCart in the x-on:submit.

And there we have it, Alpine JS powered Shopify add to cart with some extra features to offer extended flexibility to the frontend of the store.