Shopify Google Analytics Integration | OpsBlu Docs

Shopify Google Analytics Integration

How to implement Google Analytics 4 on Shopify. Covers gtag.js installation, Enhanced Measurement configuration, event tracking setup, and cross-domain...

Technical reference for implementing Google Analytics 4 (GA4) on Shopify stores, covering gtag.js loading behavior, data layer architecture, and ecommerce event configuration across all Shopify plans.

How GA4 Works on Shopify

Shopify loads analytics scripts through two distinct mechanisms depending on your plan tier:

  • Shopify Plus (native integration): Shopify injects gtag.js via the Google & YouTube sales channel. The platform pushes ecommerce events (view_item, add_to_cart, purchase) to window.dataLayer automatically using Shopify's Customer Events API. Scripts load asynchronously from https://www.googletagmanager.com/gtag/js.
  • All other plans (manual): You add the gtag.js snippet directly to theme.liquid. Shopify does not expose a built-in data layer on non-Plus plans, so ecommerce events must be constructed manually using Liquid template variables and the Shopify AJAX API (/cart.js, /products/{handle}.js).
  • Checkout pages are sandboxed on all plans except Plus. Non-Plus stores cannot inject scripts into checkout, limiting funnel tracking to the cart page and the order status (thank-you) page via Settings > Checkout > Order status page > Additional scripts.

Shopify's storefront uses a multi-domain architecture: the storefront runs on your custom domain while checkout runs on checkout.shopify.com. This domain split requires cross-domain tracking configuration or referral exclusions in GA4 to prevent session fragmentation.

Installation Methods

Method 1: Native Shopify Integration (Shopify Plus Only)

Shopify Plus stores can connect GA4 directly through the admin panel.

Step 1: Connect Google Analytics

  1. Log in to your Shopify Admin
  2. Navigate to Settings > Apps and sales channels
  3. Click Google channel
  4. Click Connect Google Account
  5. Authorize Shopify to access your Google Account

Step 2: Select GA4 Property

  1. After connecting, click Connect under Google Analytics
  2. Select your GA4 property from the dropdown
  3. Click Connect
  4. Shopify will automatically configure ecommerce tracking

Step 3: Enable Enhanced Conversions (Optional)

  1. In the Google channel settings, enable Enhanced conversions
  2. This sends hashed customer data for better attribution
  3. Click Save

Method 2: Manual Installation (All Shopify Plans)

For Shopify Basic, Shopify, and Advanced plans, use manual installation.

Step 1: Add GA4 to Theme Code

  1. Go to Online Store > Themes
  2. Click Actions > Edit code on your active theme
  3. Open theme.liquid file
  4. Add the following code before the closing </head> tag:
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-XXXXXXXXXX', {
    'send_page_view': true,
    'cookie_flags': 'SameSite=None;Secure'
  });
</script>
  1. Replace G-XXXXXXXXXX with your Measurement ID
  2. Click Save

GTM provides maximum flexibility for complex tracking needs.

Step 1: Add GTM Container

  1. Go to Online Store > Themes > Edit code
  2. Open theme.liquid
  3. Add GTM container code in <head>:
<!-- Google Tag Manager -->
<script>(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-XXXXXX');</script>
<!-- End Google Tag Manager -->
  1. Add noscript code after opening <body>:
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->

Ecommerce Tracking Configuration

Automatic Enhanced Ecommerce (Shopify Plus)

Shopify Plus automatically tracks these events when using native integration:

  • view_item_list - Collection/search page views
  • view_item - Product page views
  • add_to_cart - Add to cart actions
  • begin_checkout - Checkout initiation
  • add_shipping_info - Shipping method selection
  • add_payment_info - Payment method selection
  • purchase - Completed transactions

Manual Ecommerce Tracking (All Plans)

For non-Plus plans, implement manual tracking in theme code.

Product Page View Tracking

Add to product.liquid or product section:

<script>
  {% if product %}
  gtag('event', 'view_item', {
    'currency': '{{ cart.currency.iso_code }}',
    'value': {{ product.price | money_without_currency | remove: ',' }},
    'items': [{
      'item_id': '{{ product.id }}',
      'item_name': '{{ product.title | escape }}',
      'item_brand': '{{ product.vendor | escape }}',
      'item_category': '{{ product.type | escape }}',
      'price': {{ product.price | money_without_currency | remove: ',' }},
      'currency': '{{ cart.currency.iso_code }}'
    }]
  });
  {% endif %}
</script>

Collection Page Tracking

Add to collection.liquid:

<script>
  gtag('event', 'view_item_list', {
    'item_list_name': '{{ collection.title | escape }}',
    'items': [
      {% for product in collection.products limit: 20 %}
      {
        'item_id': '{{ product.id }}',
        'item_name': '{{ product.title | escape }}',
        'item_brand': '{{ product.vendor | escape }}',
        'item_category': '{{ product.type | escape }}',
        'price': {{ product.price | money_without_currency | remove: ',' }},
        'index': {{ forloop.index }}
      }{% unless forloop.last %},{% endunless %}
      {% endfor %}
    ]
  });
</script>

Add to Cart Tracking

Add to theme JavaScript (in theme.js or custom script):

document.addEventListener('DOMContentLoaded', function() {
  // Track add to cart on product forms
  document.querySelectorAll('form[action*="/cart/add"]').forEach(function(form) {
    form.addEventListener('submit', function(e) {
      var formData = new FormData(form);
      var productId = formData.get('id');
      var quantity = formData.get('quantity') || 1;

      fetch('/products/' + productId + '.js')
        .then(response => response.json())
        .then(product => {
          gtag('event', 'add_to_cart', {
            'currency': Shopify.currency.active,
            'value': product.price / 100,
            'items': [{
              'item_id': product.id,
              'item_name': product.title,
              'item_variant': product.variant_title,
              'price': product.price / 100,
              'quantity': quantity
            }]
          });
        });
    });
  });
});

Purchase Tracking

Add to Settings > Checkout > Order status page additional scripts:

<script>
  {% if first_time_accessed %}
  gtag('event', 'purchase', {
    'transaction_id': '{{ order.order_number }}',
    'value': {{ total_price | money_without_currency | remove: ',' }},
    'tax': {{ tax_price | money_without_currency | remove: ',' }},
    'shipping': {{ shipping_price | money_without_currency | remove: ',' }},
    'currency': '{{ currency }}',
    'coupon': '{{ discount_applications[0].title }}',
    'items': [
      {% for line_item in line_items %}
      {
        'item_id': '{{ line_item.product_id }}',
        'item_name': '{{ line_item.title | escape }}',
        'item_variant': '{{ line_item.variant_title | escape }}',
        'item_brand': '{{ line_item.vendor | escape }}',
        'price': {{ line_item.final_price | money_without_currency | remove: ',' }},
        'quantity': {{ line_item.quantity }}
      }{% unless forloop.last %},{% endunless %}
      {% endfor %}
    ]
  });
  {% endif %}
</script>

Advanced Event Tracking

Begin Checkout Event

Add to cart page (cart.liquid):

<script>
  document.querySelector('form[action="/checkout"]').addEventListener('submit', function() {
    gtag('event', 'begin_checkout', {
      'currency': '{{ cart.currency.iso_code }}',
      'value': {{ cart.total_price | money_without_currency | remove: ',' }},
      'items': [
        {% for item in cart.items %}
        {
          'item_id': '{{ item.product_id }}',
          'item_name': '{{ item.title | escape }}',
          'price': {{ item.final_price | money_without_currency | remove: ',' }},
          'quantity': {{ item.quantity }}
        }{% unless forloop.last %},{% endunless %}
        {% endfor %}
      ]
    });
  });
</script>

Search Tracking

Add to search results page:

<script>
  {% if search.performed %}
  gtag('event', 'search', {
    'search_term': '{{ search.terms | escape }}',
    'results_count': {{ search.results_count }}
  });
  {% endif %}
</script>

Newsletter Signup

Track newsletter form submissions:

<script>
  document.querySelectorAll('form[action*="/contact"]').forEach(function(form) {
    form.addEventListener('submit', function() {
      var email = form.querySelector('input[type="email"]').value;
      if (email) {
        gtag('event', 'newsletter_signup', {
          'method': 'footer_form'
        });
      }
    });
  });
</script>

Customer Login

Track customer authentication:

<script>
  {% if customer %}
  gtag('event', 'login', {
    'method': 'Shopify'
  });

  // Set user ID for cross-device tracking
  gtag('config', 'G-XXXXXXXXXX', {
    'user_id': '{{ customer.id }}'
  });
  {% endif %}
</script>

Shopify-Specific Configurations

Multi-Currency Tracking

Ensure correct currency tracking:

<script>
  gtag('config', 'G-XXXXXXXXXX', {
    'currency': '{{ cart.currency.iso_code }}'
  });
</script>

Customer Properties

Track customer segments:

<script>
  {% if customer %}
  gtag('set', 'user_properties', {
    'customer_type': '{% if customer.orders_count > 0 %}returning{% else %}new{% endif %}',
    'customer_tags': '{{ customer.tags | join: ", " }}',
    'total_orders': {{ customer.orders_count }}
  });
  {% endif %}
</script>

Discount Code Tracking

Monitor discount code usage:

<script>
  {% if cart.cart_level_discount_applications.size > 0 %}
  gtag('event', 'coupon_applied', {
    'coupon_code': '{{ cart.cart_level_discount_applications[0].title }}',
    'discount_amount': {{ cart.cart_level_discount_applications[0].total_allocated_amount | money_without_currency | remove: ',' }}
  });
  {% endif %}
</script>

Troubleshooting

Tracking Not Working

Issue: No data appearing in GA4

Solutions:

  1. Verify Measurement ID is correct (starts with G-)
  2. Check theme.liquid was saved properly
  3. Clear browser cache and test in incognito mode
  4. Verify tracking code appears in page source
  5. Check for JavaScript errors in browser console
  6. Ensure theme doesn't have conflicting scripts

Duplicate Page Views

Issue: Multiple page views for single visit

Solutions:

  1. Check for duplicate GA4 code in theme
  2. Remove GA4 from Shopify admin if using manual installation
  3. Verify GTM isn't also loading GA4
  4. Check for GA4 code in sections and snippets
  5. Review third-party apps that may add tracking

Purchase Events Not Firing

Issue: Transactions not appearing in GA4

Solutions:

  1. Verify code is in Order status page additional scripts
  2. Check {% if first_time_accessed %} tag is present
  3. Test with actual purchase (not just preview)
  4. Verify Shopify Checkout settings allow additional scripts
  5. Check currency formatting (remove commas from amounts)
  6. Test in GA4 DebugView with real transaction

Checkout Tracking Missing (Non-Plus)

Issue: Can't track checkout steps

Solutions:

  1. Shopify Basic/Standard can't modify checkout pages
  2. Only track begin_checkout from cart page
  3. Track purchase on order status page
  4. Consider upgrading to Shopify Plus for full tracking
  5. Use Shopify Analytics as supplement for checkout data

Cross-Domain Tracking Issues

Issue: Sessions breaking between checkout and storefront

Solutions:

  1. Enable cross-domain tracking in GA4 configuration
  2. Add checkout.shopify.com to linker domains
  3. Verify cookies aren't blocked
  4. Check referral exclusion list includes Shopify domains
  5. Test with Chrome DevTools to verify parameters

App Conflicts

Issue: Third-party apps interfering with tracking

Solutions:

  1. Identify conflicting apps in browser console
  2. Disable apps one by one to isolate issue
  3. Check app documentation for GA4 compatibility
  4. Contact app developer for support
  5. Use GTM to manage multiple tracking codes

Testing and Verification

Test Mode Setup

Enable debug mode for testing:

<script>
  gtag('config', 'G-XXXXXXXXXX', {
    'debug_mode': true
  });
</script>

Complete Test Purchase

Verify full tracking:

  1. Add product to cart from collection page
  2. Proceed to checkout
  3. Complete test purchase
  4. Check GA4 DebugView for all events
  5. Verify purchase in Monetization reports

Use Shopify's Test Orders

  1. Enable test mode in Shopify Payments
  2. Use test credit card: 1 (Bogus Gateway)
  3. Complete test transaction
  4. Verify events fire correctly
  5. Cancel test order afterward

Browser Console Testing

Check tracking in console:

// View dataLayer
console.log(window.dataLayer);

// Test event manually
gtag('event', 'test_event', {'test': 'value'});

Best Practices

Prevent Duplicate Purchases

Use first_time_accessed to avoid duplicate tracking:

{% if first_time_accessed %}
  // Track purchase only once
{% endif %}

Handle Dynamic Checkout Buttons

Track "Buy Now" and dynamic checkout:

document.querySelectorAll('.shopify-payment-button').forEach(function(btn) {
  btn.addEventListener('click', function() {
    gtag('event', 'dynamic_checkout_clicked', {
      'checkout_type': 'shopify_pay'
    });
  });
});

Track Quantity Changes

Monitor cart quantity updates:

document.addEventListener('cart:updated', function(event) {
  gtag('event', 'cart_updated', {
    'cart_value': event.detail.cart.total_price / 100,
    'item_count': event.detail.cart.item_count
  });
});

Product Variant Tracking

Include variant information:

'item_variant': '{{ product.selected_or_first_available_variant.title }}'

Shopify Plus Features

Enhanced Checkout Tracking

Shopify Plus allows checkout.liquid customization:

<!-- Add to checkout.liquid -->
<script>
  Shopify.Checkout.step === 'contact_information' && gtag('event', 'checkout_step', {'step': 1});
  Shopify.Checkout.step === 'shipping_method' && gtag('event', 'checkout_step', {'step': 2});
  Shopify.Checkout.step === 'payment_method' && gtag('event', 'checkout_step', {'step': 3});
</script>

Scripts API

Use Scripts API for advanced tracking without theme modifications.