Google Tag Manager Setup on BigCommerce | Blue Frog Docs

Google Tag Manager Setup on BigCommerce

Complete guide to implementing Google Tag Manager on BigCommerce using Script Manager and Stencil themes.

Google Tag Manager Setup on BigCommerce

Google Tag Manager (GTM) provides a centralized way to manage all your tracking tags and marketing pixels on BigCommerce without constantly modifying theme code.

Why Use GTM on BigCommerce?

Benefits

  • Centralized Tag Management: Manage all tags (GA4, Meta Pixel, LinkedIn, etc.) in one place
  • No Code Deployments: Add or modify tags without theme changes
  • Version Control: Track changes, rollback if needed
  • Testing & Debugging: Preview mode to test tags before publishing
  • Conditional Loading: Fire tags based on specific conditions (page type, user action, etc.)
  • Data Layer Integration: Access structured BigCommerce data for advanced tracking

When to Use GTM vs. Script Manager

Use GTM when:

  • Managing multiple tracking tags (GA4, Meta, LinkedIn, TikTok, etc.)
  • Need conditional tag firing based on user behavior
  • Require advanced tracking with data layer variables
  • Marketing team needs to manage tags independently
  • A/B testing or experimentation platforms are used

Use Script Manager when:

  • Only implementing one or two simple tracking scripts
  • No conditional logic required
  • Development team prefers direct script control
  • Simpler infrastructure is preferred

Prerequisites

  1. Google Tag Manager Account:

    • Create a free account at tagmanager.google.com
    • Create a new container for your BigCommerce store
    • Note your Container ID (format: GTM-XXXXXXX)
  2. BigCommerce Store Access:

    • Admin access to install GTM
    • Access to Script Manager or theme files
  3. Choose Implementation Method:

    • Script Manager (easier, no theme changes)
    • Stencil Theme (advanced, better data layer integration)

The easiest method to implement GTM without modifying your theme.

Step 1: Add GTM Container

  1. Navigate to Script Manager:

    • Go to Storefront > Script Manager
    • Click Create a Script
  2. Configure GTM Head Script:

    • Name: Google Tag Manager - Head
    • Description: GTM container - must load in head
    • Location: Header
    • Script Category: Analytics
    • Script Type: Script
  3. Add GTM Head Code:

<!-- 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-XXXXXXX');</script>
<!-- End Google Tag Manager -->

Replace GTM-XXXXXXX with your actual Container ID.

  1. Set Placement:

    • All Pages
  2. Save and Activate

Step 2: Add GTM Body Script

  1. Create Another Script:

    • Click Create a Script
  2. Configure GTM Body Script:

    • Name: Google Tag Manager - Body
    • Description: GTM noscript fallback
    • Location: Footer (as close to opening <body> as possible)
    • Script Category: Analytics
    • Script Type: Script
  3. Add GTM Body Code:

<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
  1. Set Placement:

    • All Pages
  2. Save and Activate

Step 3: Verify GTM Installation

  1. Install Google Tag Assistant:

  2. Use GTM Preview Mode:

    • In GTM, click Preview
    • Enter your store URL
    • Click Connect
    • New tab opens with GTM debug panel
    • Verify container loads and fires
  3. Check GTM Status:

    • GTM debug panel shows "Container Loaded"
    • "Container Version" displays current version number
    • No errors in console

Method 2: Stencil Theme Implementation (Advanced)

For full control and better data layer integration, add GTM directly to your Stencil theme.

Step 1: Set Up Stencil CLI

# Install Stencil CLI
npm install -g @bigcommerce/stencil-cli

# Download and initialize theme
stencil init
stencil start

Step 2: Add GTM to Base Template

File: templates/layout/base.html

Add GTM head script in the <head> section, before the closing </head> tag:

{{!-- ... existing head content ... --}}

{{!-- 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-XXXXXXX');</script>
{{!-- End Google Tag Manager --}}

</head>

Add GTM body script immediately after the opening <body> tag:

<body>

{{!-- Google Tag Manager (noscript) --}}
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
{{!-- End Google Tag Manager (noscript) --}}

{{!-- ... rest of body content ... --}}

Step 3: Add BigCommerce Data Layer

Create a data layer to pass BigCommerce context to GTM.

File: templates/layout/base.html (add before GTM container script)

{{!-- BigCommerce Data Layer --}}
<script>
  window.dataLayer = window.dataLayer || [];

  // Push page context
  dataLayer.push({
    'event': 'pageview',
    'pageType': '{{template}}',
    {{#if customer}}
    'customerLoggedIn': true,
    'customerId': '{{customer.id}}',
    'customerEmail': '{{customer.email}}',
    'customerGroup': '{{customer.customer_group_name}}',
    {{else}}
    'customerLoggedIn': false,
    {{/if}}
    'currency': '{{currency.code}}',
    'storeName': '{{settings.store_name}}'
  });
</script>
{{!-- End BigCommerce Data Layer --}}

{{!-- GTM Container (as shown above) --}}

Step 4: Deploy Theme

# Bundle theme
stencil bundle

# Upload via BigCommerce admin
# Storefront > Themes > Upload Theme

Adding GTM to Checkout (Plus, Pro, Enterprise Plans)

BigCommerce's optimized checkout is hosted separately and requires additional GTM installation.

Step 1: Access Checkout Settings

  1. Go to Settings > Checkout
  2. Scroll to Checkout Scripts section

Step 2: Add GTM Head Script

In Header Scripts, add:

<!-- 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-XXXXXXX');</script>
<!-- End Google Tag Manager -->

Step 3: Add GTM Body Script

In Footer Scripts, add:

<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->

Step 4: Add Checkout Data Layer

In Header Scripts, add before GTM container:

<script>
  window.dataLayer = window.dataLayer || [];

  // Poll for BigCommerce checkout data
  (function checkForCheckoutData() {
    if (typeof BCData !== 'undefined' && BCData.checkout) {
      dataLayer.push({
        'event': 'checkoutPageview',
        'pageType': 'checkout',
        'checkoutStep': window.location.pathname.includes('order-confirmation') ? 'confirmation' : 'checkout',
        'cartTotal': BCData.checkout.cart.baseAmount,
        'currency': BCData.checkout.cart.currency.code,
        'itemCount': BCData.checkout.cart.lineItems.physicalItems.length
      });
    } else {
      setTimeout(checkForCheckoutData, 100);
    }
  })();
</script>

Configuring Tags in GTM

Once GTM is installed, configure your marketing tags.

Example: Add Google Analytics 4

  1. In GTM, go to Tags > New

  2. Configure Tag:

    • Tag Type: Google Analytics: GA4 Configuration
    • Measurement ID: G-XXXXXXXXXX
    • Configuration Settings: Add any custom parameters
  3. Set Trigger:

    • Trigger Type: All Pages
    • Or use custom triggers based on data layer events
  4. Save and Publish

Example: Add Meta Pixel

  1. Create New Tag:

    • Tag Type: Custom HTML
  2. Add Meta Pixel Code:

<!-- Meta Pixel Code -->
<script>
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', 'YOUR_PIXEL_ID');
fbq('track', 'PageView');
</script>
<!-- End Meta Pixel Code -->
  1. Set Trigger: All Pages

  2. Save and Publish

GTM Best Practices for BigCommerce

1. Use Data Layer Variables

Instead of scraping DOM, use data layer variables:

// GOOD: Use data layer
dataLayer.push({
  'productId': '{{product.id}}',
  'productName': '{{product.name}}'
});

// BAD: Scrape DOM
var productName = document.querySelector('.product-title').textContent;

For GDPR/CCPA compliance, use Google Consent Mode:

<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}

  // Default consent state
  gtag('consent', 'default', {
    'analytics_storage': 'denied',
    'ad_storage': 'denied',
    'ad_user_data': 'denied',
    'ad_personalization': 'denied',
    'wait_for_update': 500
  });

  // Update based on user consent
  // (integrate with your consent management platform)
</script>

3. Version Control

  • Always use GTM's version naming and descriptions
  • Test in Preview mode before publishing
  • Create a new version for each significant change
  • Document changes in version notes

4. Organize with Folders

Create folders in GTM for better organization:

  • Analytics (GA4, Google Ads, etc.)
  • Advertising (Meta, LinkedIn, TikTok, etc.)
  • Utilities (scroll tracking, click tracking, etc.)
  • Testing (experimental tags)

5. Use Tag Sequencing

For tags that depend on others:

  1. Click Advanced Settings in tag configuration
  2. Set Setup Tags and Cleanup Tags
  3. Ensure critical tags load first

Testing GTM Implementation

1. Use Preview Mode

  1. In GTM, click Preview
  2. Enter your store URL
  3. Browse your store
  4. Check debug panel for:
    • Tags firing correctly
    • Data layer variables populating
    • No errors

2. Test Tag Firing

Verify each tag fires:

  • GA4: Check Tag Assistant or GA4 DebugView
  • Meta Pixel: Use Meta Pixel Helper extension
  • LinkedIn: Use LinkedIn Insight Tag Helper

3. Test Across All Page Types

Test on:

  • Homepage
  • Category pages
  • Product pages
  • Cart
  • Checkout (if accessible)
  • Order confirmation
  • Search results
  • 404 page

4. Verify Data Layer

In browser console:

// Check data layer exists
console.log(window.dataLayer);

// Check specific values
dataLayer.find(item => item.event === 'pageview');

Troubleshooting

GTM Container Not Loading

Symptoms: Tag Assistant shows no GTM container

Solutions:

  1. Check Script Manager scripts are Active
  2. Clear BigCommerce cache: Server Settings > Performance
  3. Verify Container ID is correct (GTM-XXXXXXX)
  4. Check for JavaScript errors in browser console
  5. Test in incognito mode to rule out browser extensions

Tags Not Firing

Symptoms: GTM loads but tags don't fire

Solutions:

  1. Check tag triggers are configured correctly
  2. Verify trigger conditions match current page
  3. Use GTM Preview mode to debug
  4. Check for JavaScript errors blocking execution
  5. Ensure tag priorities are set if using dependencies

Data Layer Variables Empty

Symptoms: Data layer exists but variables are undefined

Solutions:

  1. Check Stencil context is available when data layer pushes
  2. Verify Handlebars syntax is correct
  3. Ensure data layer push happens before GTM container loads
  4. Use browser console to inspect dataLayer array

Checkout Tracking Not Working

Symptoms: GTM works on storefront but not checkout

Solutions:

  1. Verify your plan supports checkout scripts (Plus, Pro, Enterprise)
  2. Check scripts are in correct sections (Header Scripts vs Footer Scripts)
  3. Ensure GTM container ID matches storefront implementation
  4. Test checkout in Preview mode
  5. Check BCData object exists on checkout pages

Duplicate Tags Firing

Symptoms: Same tag fires multiple times

Solutions:

  1. Check for GTM implementation in multiple places (theme + Script Manager)
  2. Verify triggers aren't overlapping
  3. Remove duplicate GTM containers
  4. Use tag sequencing to control execution order

Security Considerations

Protect Sensitive Data

Never send to data layer:

  • Credit card numbers
  • Passwords
  • Social Security numbers
  • Full payment details

Hash Personal Information

For user IDs and emails:

// Hash email before sending
async function hashEmail(email) {
  const msgBuffer = new TextEncoder().encode(email.toLowerCase());
  const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}

// Usage in data layer
hashEmail('{{customer.email}}').then(hash => {
  dataLayer.push({
    'hashedEmail': hash
  });
});

Limit GTM Permissions

  • Only grant GTM access to necessary team members
  • Use GTM user permissions appropriately:
    • Publish: Marketing leads only
    • Edit: Marketing team
    • Read: Stakeholders
  • Enable 2-Step Verification on Google accounts with GTM access

Next Steps

Additional Resources

// SYS.FOOTER