Add multiple products, subscriptions and qty to a Shopify cart, via Javascript Cart API

A quick way to add multiple items to a customers cart without redirecting the customer to the cart page

Rob Johnson

By Rob Johnson

Fri Sep 30 2022

You can use the following javascript which uses Shopify's Cart API to add multiple products to your cart with one click of a button.

Javascript function to add to global.js

// add to cart function that keeps customer on the same page
Shopify.addToCart = function(items) {
	fetch(window.Shopify.routes.root + 'cart/add.js', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(items)
  })
  .then(response => {
    return response.json();
  })
  .catch((error) => {
    console.error('Error:', error);
  });
};

Create an object array that will contain all the products that you want to add to the cart.

id represents the variant ID.

You can also add subscription items if you also add a selling_plan ID which is created in Shopify when setting up a subscription and is required when adding a subscription product to the cart.

let products = {
 'items': [{
    'id': 111,
    'quantity': 4
  },
  {
    'id': 41618559008930,
    'selling_plan': 222,
    'quantity': 2
  }]
};

If needed, you can add another item to the products object by using push().

products.items.push({id: 333, quantity:5})

Which will add the product to the products object, in the items array which will be formatted correctly for Shopify's Cart API.

You can also use pop() to remove the last item in the array, or just destroy and recreate the products object if you want to start over again.

products.items.pop()

Adding the products to the cart

Once you have the object all ready, adding the items to the cart is a simple call to the function that we made earlier.

Shopify.addToCart(products)

There is more functionality available in the Shopify documentation for Cart API, such as:

I think there are some really interesting applications that this can be used for that are not prevalent in common shopping experiences today.

# commerce 14 # seo 5 # tools 6 # amazon 1 # sql 4 # shopify 9 # javascript 13 # projects 4 # css 2 # git 2 # php 3 # analytics 4 # api 6 # monitoring 2 # python 2 # aws 2