🏢 Meet the Client
I built this setup for Dropbearcoolers. They sell insulated cooler bags and when customers purchase a bag, they wanted to offer a free drink bottle as a gift.
🚧 Pain Point
Dropbear Coolers didn't want to use an app since most third-party apps aren't compatible with cart drawer. When apps add the free gift to cart, they reload the page. Which is annoying and creates a poor user experience. Additionally, they wanted the free gift to be added to the customer's cart automatically.
🛠️ The Solution (What I Did)
I started by creating a Shopify automatic discount using the “Buy X Get Y” discount type. This allowed the store to offer customers a free item when they purchased a specific product (for instance bag) or met a required quantity threshold.
According to Shopify’s discount rule, customers must add the quantity of items specified below to their cart. Meaning, customers had to manually add the free bottle to their cart and quantity must match for the discount to apply.
According to Dropbear's requirements, they didn't want customers to manually add items. Instead, they wanted the free item to be added automatically when someone purchases any item from the cooler collection.
Let’s see it in practice: (Technical guide)
According to the discount rule, if customers buy any item from the cooler collection, they get the bottle as a free gift. So, we'll need the collection data and all products within this collection, so that we can take action whenever any item from this collection is added to the cart.
To simplify things, I created a custom API endpoint within Shopify without requiring external APIs.
Then I use JavaScript’s
async/await
to call this endpoint asynchronouslyLet me explain what is going on here.
We start by listening for the product-ajax:added event. This event fires every time a product is added to the cart using AJAX.
Inside the event handler, we grab the handle of the product that was just added to the cart. We also define the handle of the free gift item, which in this case is a water bottle
We then call our fetchCoolers function, which fetches all products in the ‘coolers’ collection. Once we have the data, we check if the product that was just added is part of that collection.
If the product is in the coolers collection, we fetch the current cart contents. If the discount product isn’t in the cart yet, we send a POST request to Shopify’s /cart/add.js
endpoint to add it.
After adding the discount product, we dispatch a custom event called cart:refresh. This tells the rest of the theme to update the cart UI, so the customer sees the new item right away.