Skip to content

Google AdsPublished 14 min read

Shopify Custom Pixel Google Tag Manager Setup Guide

How to load GTM inside a Shopify custom pixel, push clean dataLayer events, fix the sandbox page URL, respect consent and test it without a working preview mode.

Muhammad Qitmeer, founder of Augere Labs
Muhammad Qitmeer
Co-founder and CEO, Augere Labs
Share

To run a Shopify custom pixel with Google Tag Manager, you paste the GTM container script (without the script tags) into a new pixel under Settings, Customer events, subscribe to Shopify's standard events with analytics.subscribe, and push each one into the dataLayer so GTM triggers can fire on it. The container runs inside Shopify's sandbox, so you also have to send your own page URL, map Shopify consent to Google consent, and test with real checkouts instead of GTM preview.

This is for agency developers and PPC managers who need GTM on a Shopify store after checkout extensibility removed theme and checkout script access. It covers how the sandbox behaves, a full pixel you can adapt, the GTM side, the page_location problem, consent, avoiding double counting with Shopify's own Google and Meta apps, and a test plan that works when preview mode does not.

Can you use Google Tag Manager in a Shopify custom pixel?

Yes, Shopify documents it, but Google does not support it, and you should know both positions before you build. Shopify's help center has a Google Tag Manager custom pixel tutorial with example code. Google's own page on the limitations of using a custom pixel on Shopify says running Tag Manager inside the custom pixel sandbox is not a supported implementation, that some events and parameters may be lost, that you may see conversion drops and attribution issues, and that Google support cannot help you troubleshoot it.

Shopify also calls custom pixels an advanced feature that it does not support either. So nobody on the platform side will debug this for you. That is fine as long as you go in with a plan:

  • Google Analytics and Google Ads. Google recommends the Google & YouTube app for these. If the client's main goal is Google Ads purchase conversions, the app is usually the safer owner.
  • Everything else. TikTok, Pinterest, Microsoft Ads, LinkedIn, affiliate tags and custom destinations are where a GTM custom pixel earns its keep, especially when the vendor's own Shopify app is weak or missing.
  • Hybrid. Plenty of stores run the Google & YouTube app for Google, the Facebook & Instagram app for Meta, and one GTM custom pixel for the rest. That split is easy to reason about and easy to hand over.

Whichever you pick, write down which tool owns which destination. Most Shopify tracking problems we see come from two tools both believing they own the purchase event.

How does the Shopify custom pixel sandbox work?

Custom pixels run inside an isolated iframe on the page, called the lax sandbox, while app pixels run in a stricter one. Your code does not run in the storefront's main window. It cannot read the theme's DOM, it cannot see buttons or forms, and GTM inside it sees the iframe, not the page the shopper is looking at.

Shopify's pixels overview lists what the sandbox cannot do automatically: render interface elements, scrape the DOM for events or customer details, detect outbound link clicks, track scrolling, or build click heatmaps. It also says automatic detection of page URLs in the lax sandbox includes a sandbox version of the URL, not the main window's URL.

What you do get is Shopify's customer events API. Inside a custom pixel these objects are available:

  • analytics. Lets you subscribe to events with analytics.subscribe(eventName, callback). You can also subscribe to groups such as all_standard_events and all_custom_events.
  • init. A snapshot of the page at render time, including context, cart and customer data, and init.customerPrivacy for the visitor's starting consent state.
  • browser. Async methods that run in the top frame, such as cookie, localStorage and sessionStorage access.
  • api.customerPrivacy. Lets you subscribe to consent changes with the visitorConsentCollected event.

The upside of the sandbox is that it also runs on checkout, the order status page and other pages theme code never reached on stores using checkout extensibility. Shopify's page_viewed event, for example, is available on online store, checkout and order status pages. That is the main reason agencies move GTM into a pixel at all.

Which Shopify customer events can GTM listen to?

GTM can listen to any of Shopify's standard events once you subscribe to them in the pixel and push them into the dataLayer. Shopify's standard events reference lists them. These are the ones that matter for ad and analytics tracking, with the closest GA4 event:

Shopify eventWhen it firesClosest GA4 eventUseful fields
page_viewedEvery page, including checkout and order statuspage_viewcontext.window.location.href, context.document.title, context.document.referrer
collection_viewedCollection page viewview_item_listdata.collection
product_viewedProduct page viewview_itemdata.productVariant (id, sku, price, product.title)
search_submittedStorefront searchsearchdata.searchResult
product_added_to_cartAdd to cartadd_to_cartdata.cartLine (quantity, cost.totalAmount, merchandise)
cart_viewedCart page viewview_cartdata.cart
checkout_startedCheckout openedbegin_checkoutdata.checkout
payment_info_submittedPayment step submittedadd_payment_infodata.checkout
checkout_completedOnce per checkout, usually the Thank you pagepurchasedata.checkout.order.id, totalPrice, currencyCode, lineItems

Two details about checkout_completed trip people up. First, Shopify fires it once per checkout. If the store uses a post-purchase upsell, it fires on the first upsell page instead of the Thank you page, and not again after. Second, if the page where it should fire fails to load, the event does not fire at all. Neither is a bug in your pixel, so do not try to "fix" them with a second trigger.

Most fields in the payload are typed as possibly null, including data.checkout.order.id and data.cartLine. Guard every read, or one missing value will throw and stop the rest of your callback.

How do you push Shopify events into the GTM dataLayer?

You define window.dataLayer, load the container, and then call window.dataLayer.push inside each analytics.subscribe callback with an event key that a GTM Custom Event trigger can match. Here is the full order of work.

  1. Copy the container code. In GTM, open Admin, then Install Google Tag Manager, and copy the head snippet. Delete the opening and closing script tags. The sandbox only accepts JavaScript.
  2. Remove old code first. Shopify asks you to remove existing pixel code from theme.liquid, checkout.liquid on Plus, and the old Additional scripts box before adding a custom pixel. A GTM snippet left in the theme will double count storefront events.
  3. Create the pixel. In Shopify admin go to Settings, then Customer events, give the pixel a unique name such as "GTM", and click Add pixel.
  4. Set customer privacy. In the Customer privacy section, choose the Permission and Data sale settings. New custom pixels default to requiring Marketing and Analytics permission. More on this choice in the consent section below.
  5. Paste the code. Use the pixel below, with your container ID in place of GTM-XXXXXXX.
  6. Save and connect. Click Save, then Connect pixel, and confirm.
  7. Build the GTM side. Create Data Layer Variables, Custom Event triggers and tags that match the keys you push, then publish the container.

This pixel handles consent, page views with the real URL, product views, add to cart, checkout start and purchase. It uses plain functions and string concatenation on purpose, so it pastes cleanly into Shopify's editor.

// 1. dataLayer and gtag stub
  window.dataLayer = window.dataLayer || [];
  function gtag() { window.dataLayer.push(arguments); }
  
  // 2. Consent: map Shopify customer privacy to Google consent
  function consentFrom(p) {
    var analytics = p && p.analyticsProcessingAllowed ? 'granted' : 'denied';
    var marketing = p && p.marketingAllowed ? 'granted' : 'denied';
    return {
      analytics_storage: analytics,
      ad_storage: marketing,
      ad_user_data: marketing,
      ad_personalization: marketing
    };
  }
  gtag('consent', 'default', consentFrom(init.customerPrivacy));
  
  api.customerPrivacy.subscribe('visitorConsentCollected', function (event) {
    gtag('consent', 'update', consentFrom(event.customerPrivacy));
  });
  
  // 3. Load the GTM container (script tags removed)
  (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');
  
  // 4. Helpers
  function money(m) { return m ? Number(m.amount) : undefined; }
  function itemFromVariant(v, qty) {
    if (!v) return {};
    return {
      item_id: v.sku || (v.product ? v.product.id : v.id),
      item_name: v.product ? v.product.title : v.title,
      item_variant: v.title,
      item_brand: v.product ? v.product.vendor : undefined,
      price: money(v.price),
      quantity: qty || 1
    };
  }
  
  // 5. Page views with the real page URL
  analytics.subscribe('page_viewed', function (event) {
    window.dataLayer.push({
      event: 'shopify_page_view',
      page_location: event.context.window.location.href,
      page_title: event.context.document.title,
      page_referrer: event.context.document.referrer
    });
  });
  
  // 6. Product view
  analytics.subscribe('product_viewed', function (event) {
    var v = event.data.productVariant;
    window.dataLayer.push({ ecommerce: null });
    window.dataLayer.push({
      event: 'shopify_view_item',
      page_location: event.context.window.location.href,
      ecommerce: {
        currency: v && v.price ? v.price.currencyCode : undefined,
        value: v ? money(v.price) : undefined,
        items: [itemFromVariant(v, 1)]
      }
    });
  });
  
  // 7. Add to cart
  analytics.subscribe('product_added_to_cart', function (event) {
    var line = event.data.cartLine;
    if (!line) return;
    window.dataLayer.push({ ecommerce: null });
    window.dataLayer.push({
      event: 'shopify_add_to_cart',
      page_location: event.context.window.location.href,
      ecommerce: {
        currency: line.cost.totalAmount.currencyCode,
        value: line.cost.totalAmount.amount,
        items: [itemFromVariant(line.merchandise, line.quantity)]
      }
    });
  });
  
  // 8. Checkout started
  analytics.subscribe('checkout_started', function (event) {
    var c = event.data.checkout;
    window.dataLayer.push({ ecommerce: null });
    window.dataLayer.push({
      event: 'shopify_begin_checkout',
      page_location: event.context.window.location.href,
      ecommerce: {
        currency: c.currencyCode,
        value: money(c.totalPrice),
        items: c.lineItems.map(function (li) { return itemFromVariant(li.variant, li.quantity); })
      }
    });
  });
  
  // 9. Purchase
  analytics.subscribe('checkout_completed', function (event) {
    var c = event.data.checkout;
    var orderId = c.order && c.order.id ? c.order.id : c.token;
    window.dataLayer.push({ ecommerce: null });
    window.dataLayer.push({
      event: 'shopify_purchase',
      page_location: event.context.window.location.href,
      user_email: c.email || undefined,
      user_phone: c.phone || undefined,
      ecommerce: {
        transaction_id: orderId,
        currency: c.currencyCode,
        value: money(c.totalPrice),
        tax: money(c.totalTax),
        shipping: c.shippingLine ? money(c.shippingLine.price) : undefined,
        items: c.lineItems.map(function (li) { return itemFromVariant(li.variant, li.quantity); })
      }
    });
  });

A few choices in that code are deliberate:

  • Prefixed event names. Pushing shopify_purchase instead of purchase keeps your triggers separate from anything GTM or a stray tag might push on its own, and makes it obvious in a dataLayer dump where each event came from.
  • Clearing ecommerce. Pushing ecommerce: null before each ecommerce event stops item arrays from one event leaking into the next, which is standard GA4 practice.
  • Order ID fallback. Shopify types order.id as nullable, so the code falls back to the checkout token. Either way, send one stable ID per order as the transaction ID so GA4 and Google Ads can deduplicate.
  • Email and phone. These are only for enhanced conversions or Meta advanced matching, and only when consent allows. If the client does not use them, delete those two lines.
  • Value. totalPrice includes tax and shipping. If the client reports revenue net of tax and shipping, use subtotalPrice or subtract the two before you push. Pick one definition and use it in every tool.

The GTM side

Shopify's tutorial is clear that the Event name in a GTM Custom Event trigger must match the event key you push. For each event:

  • Triggers. One Custom Event trigger per pushed event, for example a trigger with Event name shopify_purchase.
  • Variables. Data Layer Variables for page_location, user_email and any field you map by hand, such as ecommerce.transaction_id and ecommerce.value.
  • GA4 event tags. Event names in GA4's own vocabulary (page_view, view_item, add_to_cart, begin_checkout, purchase), with Send Ecommerce data turned on and the data source set to Data Layer.
  • Google Ads conversion tag. On the shopify_purchase trigger, with Conversion Value, Transaction ID and Currency Code mapped to your variables, plus a Conversion Linker tag on all events.

If you need to track something Shopify does not offer as a standard event, such as a click in a theme app block, publish a custom event from the theme with Shopify.analytics.publish and subscribe to it in the pixel. Shopify says it does not support adding custom data to standard events, so custom events are the only route.

Why is page_location showing the sandbox URL, and how do you fix it?

GA4 shows a sandbox URL because the Google tag reads the location of the iframe it runs in, not the storefront page. Shopify confirms that automatic page URL detection in the lax sandbox includes sandbox information, and its fix is to take the URL from the page_viewed event yourself.

The fix has two parts, and you need both:

  1. Stop the automatic page view. In your Google tag in GTM, add the configuration parameter send_page_view with the value false. Without this, the Google tag sends its own page_view with the wrong URL and you get two page views per page.
  2. Send your own page view. Create a GA4 event tag named page_view on the shopify_page_view trigger, with page_location, page_title and page_referrer mapped to the Data Layer Variables the pixel pushes.
  3. Pass page_location on every event. GA4 reports like landing page and page path also read page_location from other events, so add the parameter to your ecommerce tags too. The pixel above already pushes it on each event.
  4. Check a Realtime report. Open a few pages and look at the page path dimension. If any sandbox paths remain, a tag is still sending without your override.

Related symptom: GA4 enhanced measurement features that depend on the page, like outbound clicks and scroll, will not work from the sandbox. Shopify's tutorial says outbound link clicks must be published as custom events. Turn those enhanced measurement options off in the GA4 data stream if they are producing junk, and rebuild only the ones the client needs.

Referral data has the same root cause. If the client sees odd self-referrals or broken session attribution after the move, compare against our notes on GA4 cross-domain tracking and self-referrals and confirm page_referrer is coming from the pixel, not the iframe.

How do you handle consent in a Shopify custom pixel?

You handle it in two layers: Shopify's pixel permission decides whether the pixel loads at all, and your code maps Shopify's consent state into Google consent mode for the tags inside GTM. Shopify's pixel privacy docs describe both.

The first layer is the Permission setting in the pixel's Customer privacy section:

  • Required. The pixel only loads after the visitor grants the purposes you select, such as marketing and analytics. Simple and strict, but tags inside GTM never see the denied visitors, so Google consent mode modeling has nothing to work with.
  • Not required. The pixel always loads, and your code is responsible for passing the correct consent state to every tag. This is the option to use if the client wants consent mode with cookieless pings, but it puts the compliance burden on your setup.

The second layer is the code. init.customerPrivacy holds four booleans: analyticsProcessingAllowed, marketingAllowed, preferencesProcessingAllowed and saleOfDataAllowed. The pixel above sets a consent default from that object before GTM loads, then listens for visitorConsentCollected and sends a consent update when the shopper uses the banner.

Watch Shopify's own example here. Its tutorial sets all four Google consent types to granted unconditionally, and it warns that this might not match what your region requires. Do not ship that line to a store with EEA or UK traffic. Map from the visitor's real choice, as above. For the Google side of the settings and how to check them in Tag Assistant, see our Consent Mode v2 implementation guide. Also set the consent checks on non-Google tags in GTM, because consent mode only governs Google tags by default.

Will a GTM custom pixel duplicate the Google & YouTube and Facebook & Instagram apps?

Yes, if both send the same event to the same destination. The apps install their own app pixels, and nothing stops your GTM pixel from firing the same purchase into the same GA4 property, Google Ads conversion action or Meta pixel.

DestinationIf the app is installedWhat to do in GTM
GA4 propertyGoogle & YouTube app sends page views and ecommerce eventsDo not add a GA4 config or purchase tag for the same measurement ID. Use a different property or none.
Google Ads purchaseApp can create and send its own purchase conversionFire your tag into a separate conversion action set to secondary, or not at all. Only one action should be primary.
Meta pixelFacebook & Instagram app sends browser events and Conversions API eventsLeave Meta out of GTM. A second Purchase from GTM will not share the app's event IDs and will double count.
TikTok, Pinterest, MicrosoftCheck whether a vendor app is installedUse GTM only where no app is already sending the same event.

Before you connect the pixel, go to Settings, Customer events and list every app pixel and custom pixel on the store. Then check the Google Ads conversion actions list for more than one primary purchase action, and the GA4 data streams for more than one tag sending to the same stream. If you inherit a store that already double counts, our fix pages for Google Ads counting conversions twice and Meta duplicate events walk through the cleanup. For GA4 purchase duplicates specifically, see GA4 purchase tracking and duplicate transactions.

Does GTM preview mode work with a Shopify custom pixel?

Not reliably, so do not plan your QA around it. Shopify's tutorial says the Troubleshoot tag feature in Google Tag Assistant is not compatible with custom pixels. In practice, Tag Assistant preview often fails to connect to a container running inside the sandbox iframe, and the Shopify community has long threads of developers hitting exactly that.

That means you will test against published container versions. Work like this to keep it safe:

  1. Build in a workspace and publish small. Publish one tag group at a time with a clear version name, so a bad change is one rollback away.
  2. Use Shopify Pixel Helper. Shopify recommends its Pixel Helper extension to confirm events reach the sandbox without errors. It shows whether shopify events fire and what data they carry.
  3. Inspect the iframe in devtools. In Chrome's console, switch the context dropdown from top to the web pixel sandbox frame, then type dataLayer to see every push. This is the closest thing you have to the preview event list.
  4. Watch the network tab. Filter for collect to see GA4 hits leave the browser, and check the dl (page location) parameter is the real URL. Filter for googleadservices or the vendor's domain for ad tags.
  5. Use GA4 DebugView. Add debug_mode set to true on your Google tag while testing, then remove it before you finish.
  6. Add temporary logging. A console.log inside each subscribe callback confirms the callback ran, even when no tag fired. Remove it when you are done.

If the client runs a server-side GTM container, its preview mode works normally, because it watches the server, not the browser. That gives you a full view of incoming requests from the pixel, which is a real advantage on Shopify.

How do you test with a real order?

Place an order end to end, because checkout_completed only fires on a completed checkout and no amount of storefront clicking will exercise it. Use the store's test payment setup if it has one, or a real low-value order that you refund afterwards. Agree the approach with the client first so nobody's fulfillment team ships a test order.

Check these in order:

  • Pixel fired. Pixel Helper or the iframe console shows checkout_completed and your shopify_purchase push, with a transaction ID, value and currency.
  • Tags fired once. The network tab shows one GA4 purchase hit and one Google Ads conversion request, not two.
  • Upsell path. If the store has post-purchase upsells, place a second order and accept one. The purchase should fire on the first upsell page and not again on Thank you.
  • GA4. The purchase shows in DebugView or Realtime with the correct transaction ID and items. Monetization reports can take a day.
  • Google Ads. The conversion action status changes and the test conversion appears after the usual reporting delay. If nothing records after a day, work through Google Ads conversions not recording.
  • Consent denied. Repeat in a private window with the banner declined. Ad tags should not set cookies, and with the Required permission the pixel should not load at all.

Expect some gap between Shopify orders and tracked conversions. Google itself warns about data drops from the sandbox, ad blockers block GTM, and shoppers who close the tab before Thank you loads never fire the event. If the client depends on Google Ads bidding, back up the browser conversion with enhanced conversions, or an import from Shopify order data through offline conversion import, so lost browser hits do not starve Smart Bidding.

Getting it fixed for a client

A GTM custom pixel on Shopify works, but it sits in a gap that neither Shopify nor Google supports, and the failures are quiet: wrong page URLs, consent forced to granted, and purchases counted by both an app and the pixel. If you want a second pair of eyes on a client store, we will check the pixel code, the GTM container and the app overlap and tell you exactly what is double counting or missing. Start with a free tracking check.

Just one quick fix, not a whole account? Our founder takes small fixed-price jobs on Fiverr: Google Ads conversion tracking fix

Frequently asked questions

Where do I add Google Tag Manager in Shopify now that theme scripts do not reach checkout?

Add it as a custom pixel under Settings, Customer events in Shopify admin. Paste the GTM head snippet without the script tags, then push Shopify events into the dataLayer from analytics.subscribe callbacks.

Why does GTM not fire any tags from my Shopify custom pixel?

Usually the GTM trigger's Event name does not match the event key you push, or the container changes are not published. Preview mode does not reliably connect to the sandbox, so unpublished changes will not run.

What is the Shopify event for a purchase in a custom pixel?

It is checkout_completed. It fires once per checkout, usually on the Thank you page, or on the first upsell page when a post-purchase offer is shown.

Can I keep the Google & YouTube app and also run GA4 through a GTM custom pixel?

Only if they send to different GA4 properties. If both send to the same measurement ID, every page view and purchase is counted twice.

Does Google support GTM inside a Shopify custom pixel?

No. Google says running Tag Manager in the custom pixel sandbox is not a supported implementation and recommends the Google & YouTube app for Google measurement. Shopify documents the setup but also treats custom pixels as unsupported.

Muhammad Qitmeer

Written by

Muhammad Qitmeer, founder of Augere Labs

Augere Labs is the white-label tracking partner behind marketing agencies. If a client account has numbers you don't trust, I'm happy to look at it with you and tell you straight what's wrong.

Connect on LinkedIn