How to track the events of adding and deleting any item to cart?

I’ve created app extensions. How in js file assests track clicks add and remove from cart when my app will be installed in some store?

You need to use an observer - something like this. Depending on your needs you can store copies of the cart in local storage and compare to determine what has happened if you need specifics.

function observeCartChanges() {
  const cartObserver = new PerformanceObserver((list) => {
    list.getEntries().forEach((entry) => {
      const isValidRequestType = ['xmlhttprequest', 'fetch'].includes(entry.initiatorType);
      const isCartChangeRequest = /\/cart\//.test(entry.name);
      if (isValidRequestType && isCartChangeRequest) {
        // handle cart request
      }
    });
  });
  cartObserver.observe({ entryTypes: ["resource"] });
}

Hi @mjari519

I am from Mageplaza - Shopify solution expert.

To track add-to-cart and remove-from-cart events in a Shopify app extension, especially using the didMount.js in your extension’s assets, you need to listen to DOM events triggered by Shopify’s storefront or inject listeners for cart updates.

However, Shopify doesn’t provide direct JS events like “item added to cart” unless you’re working with a custom storefront or Online Store 2.0 theme with AJAX APIs. Here’s how you can do it:

Step-by-Step Guide to Track Add/Remove to Cart

  1. Add Event Listeners in your didMount.js:
    If your app is injected via Shopify’s app extension or script tag, use JavaScript to hook into add/remove actions.
// Monitor add to cart button
document.addEventListener('click', function(event) {
  const target = event.target;

  // Adjust selector based on theme's button structure
  if (target.matches('form[action*="/cart/add"] [type="submit"], button.add-to-cart')) {
    console.log('Add to Cart Clicked:', target);
    
    // Optional: send to your backend or analytics
  }
});

// Intercept cart changes via Shopify AJAX API
(function() {
  const originalFetch = window.fetch;
  window.fetch = function() {
    const url = arguments[0];

    // Monitor AJAX add to cart
    if (typeof url === 'string' && url.includes('/cart/add')) {
      console.log('Item is being added via AJAX');
    }

    // Monitor AJAX remove from cart
    if (typeof url === 'string' && url.includes('/cart/change')) {
      console.log('Cart item is being changed (quantity set to 0 = remove)');
    }

    return originalFetch.apply(this, arguments);
  };
})();
  1. Optional: Use Shopify AJAX API Directly (Online Store 2.0)
    You can poll or monitor /cart.js or use endpoints like:
  • POST /cart/add.js – item added
  • POST /cart/change.js – item quantity changed or removed
fetch('/cart.js')
  .then(res => res.json())
  .then(cart => {
    console.log('Current cart state:', cart);
  });
  1. Where to Place This
    Since your didMount.js is inside assets/, make sure:
  • It’s included in the relevant Liquid file (cross_sell.liquid, up_sell.liquid)
  • Example inclusion:

  1. Next Steps
    You may also want to log these events to your backend, e.g., via fetch(‘/your-server-endpoint’, {…}).

Please let me know if it works as expected!

Best regards!