by Tobe Osakwe Mar 9, 2025

Screenshot of the cart discount code field we created, in the Dawn theme.
Screenshot of the cart discount code field we created, in the Dawn theme.

In e-commerce, it’s important in to squeeze out every possible conversion. In Shopify, customers have to wait until checkout to apply discount codes, which can lead to abandoned carts. We’ve come up with a clever workaround to let customers enter discount codes when they reach the cart page. It works in all themes, doesn’t require an app, and this snippet is pretty easy to add to your theme.

(If you like this, you might also like our app, Regios Discounts).

How to Add a Discount Code Field to Your Shopify Cart

The key here: Shopify allows you to create shareable links like yoursite.com/discount/CODE that automatically apply discounts to the cart. By using this functionality, you can set up a system where discounts can be applied instantly as soon as a customer enters a code in the cart.

Then, you can use the AJAX Cart API to automatically check if the discount got applied to the order. If it wasn’t, it wasn’t a real code.

Step 1: Add the HTML Code

To begin, you’ll need to add a simple form to your cart page where customers can enter their discount codes. If you’re using the Dawn theme, insert this HTML into your main-cart-footer.liquid file within the <div class="cart__blocks">, before the {% for block in section.blocks %}:

<form id="cart-discount-form" style="text-align: right">
  <div>
    <label for="discount-code-input">Enter a discount code:</label>
  </div>
  <div style="display: flex">
    <input id="discount-code-input" placeholder="Discount code" required />
    <button type="submit">Apply</button>
  </div>
  <p id="discount-code-success" style="color: green; display: none;"></p>
  <p id="discount-code-error" style="color: red; display: none;"></p>
</form>

Step 2: Add the JavaScript Code

Now, add this JavaScript to make the discount field functional. It checks if the discount is successfully applied using Shopify’s AJAX Cart API. Place this script in a <script> tag just before the {% schema %} in your main-cart-footer.liquid file:

<script>
document.addEventListener('DOMContentLoaded', function () {
  const discountCodeForm = document.querySelector('#cart-discount-form');
  const discountCodeInput = document.querySelector('#discount-code-input');
  const discountCodeSuccess = document.querySelector('#discount-code-success');
  const discountCodeError = document.querySelector('#discount-code-error');

  // / Hide both success and error messages initially
  const hideMessages = () => {
    discountCodeSuccess.style.display = "none";
    discountCodeError.style.display = "none";
  };

  // Function to display error messages
  const showError = (msg) => {
    discountCodeError.textContent = msg;
    discountCodeError.style.removeProperty('display');
  };

  // Function to display success messages
  const showSuccess = (msg) => {
    discountCodeSuccess.textContent = msg;
    discountCodeSuccess.style.removeProperty('display');
  };

  // Request data from the server. Throw a labeled error if it fails.
  const fetchOrShowError = async (label, url) => {
    const localeAwareUrl = window.Shopify.routes.root + url;
    const response = await fetch(localeAwareUrl);
    if (!response.ok) {
      throw new Error(`${label} failed: ${response.status} ${response.statusText}`);
    }
    return response;
  };

  // Check the cart to see if a specific discount code has been applied.
  const checkForDiscount = (cart, code) => {
    // Check for order-level discounts
    if (cart.cart_level_discount_applications
        && cart.cart_level_discount_applications.some((app) => app.title === code)) {
      return true;
    }

    // Check for line item discounts
    if (cart.items.some((item) => item.discounts?.some((discount) => discount.title === code))) {
      return true;
    }

    return false;
  };

  // Intercept the form being submitted and apply the discount code.
  discountCodeForm.onsubmit = async (e) => {
    e.preventDefault();
    hideMessages();

    // Field must not be empty
    const code = discountCodeInput.value.trim();
    if (!code) {
      showError('Enter a discount code');
      return;
    }

    try {
      await fetchOrShowError('Discount application', `discount/${code}`);

      // Check if the discount was actually applied instead just assuming it
      // succeeded.
      const cartResponse = await fetchOrShowError('Cart fetch', 'cart.js');
      const cart = await cartResponse.json();

      if (checkForDiscount(cart, code)) {
        showSuccess('Discount applied! Reloading the page...');
        location.reload();
      } else {
        showError('Enter a valid discount code');
      }
    } catch(e) {
      showError(e);
    }
  };
});
</script>

Caveats

  • This solution doesn’t automatically integrate with third-party cart drawers. This is because you can’t edit the code of 3rd party app blocks/app embeds.
  • You’ll need to style the discount code field yourself with CSS. to match your store’s branding. What we’ve provided here is pretty barebones.
  • When possible, use automatic discounts instead of manual codes. You can also display them on product pages to improve conversion rate even more than a discount code field in the cart could. This isn’t available in base Shopify, but our app provides this.

Looking for an app to do this?

  • While our app, Regios Discounts, does not currently support this feature directly, there is an open feature request that we encourage you to upvote and comment on if you want us to add this functionality. Check it out here.

Conclusion

This simple trick lets your customers use discount codes earlier, making shopping smoother and helping you sell more. Try it out and see the difference it makes in your store!

For even more discount options, check out our app, Regios Discounts—the most comprehensive discounting tool on Shopify.

Install now