dataLayer undefined on checkout pages even after adding gtm code in custom pixel

Hi,

I am using custom pixels to track checkout-related GTM events. This is the code for one of the events.

(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXXX');

window.dataLayer = window.dataLayer || [];

 analytics.subscribe("checkout_shipping_info_submitted", event => {
   window.dataLayer.push({ ecommerce: null })
   
   window.dataLayer.push({
    event: 'add_shipping_info',
     currency: event.data.checkout.currencyCode,
     value: event.data.checkout.subtotalPrice.amount,
     items: event.data.checkout.lineItems.map((product) => {
          // details of each product in cart
          return {
            item_id: product.id,
            item_name: product.title,
            price: product.variant.price.amount,
            quantity: product.quantity
          }
        })
    });
 });

As you can see I have added the GTM installation code, however when I am on the checkout page and I enter dataLayer into the console, it says the dataLayer is undefined. Does anyone know why this is happening? Am I supposed to add the GTM installation code somewhere else?

Thank you!

@Nabihah_1 unless you have Shopify Plus there’s no way to inject scripts into the checkout process itself, only the confirmation page. So your installation code is likely not present on the checkout page you’re working on. That said, Shopify recently released support for GA4 (through an app). If you haven’t done so already, I would suggest setting up GA4 that way because it may be able to track what you want to track without writing code for it.

We have Shopify Plus! Where can I inject scripts in the checkout process if I have Shopify Plus?Because I only see a place to add scripts for post purchase tracking and on the order status page, not on the information, payment, or shipping pages.

The old way is by editing checkout.liquid in your theme (add your installation code there). But that’s being deprecated next year. The replacement is “checkout extensibility”.

Our store is using checkout extensibility but I do not see a place to add code. They just have an editor where you can change appearances, add branding, etc.

I haven’t used checkout extensibility, but I think this is what you’re looking for. Sounds like they would recommend using the Google & YouTube app, but you could probably add GA4 as a custom pixel if you wanted to.