Squarespace GTM Integration | Blue Frog Docs

Squarespace GTM Integration

Integrate Google Tag Manager with Squarespace for centralized tag management.

Squarespace GTM Integration

Complete guide to setting up Google Tag Manager (GTM) on your Squarespace site for centralized tracking and tag management.

Overview

Google Tag Manager provides a centralized solution for managing tracking codes on your Squarespace website. Instead of adding individual tracking scripts through Squarespace's built-in integrations or code injection, GTM lets you control everything from one interface.

Why Use GTM with Squarespace?

GTM provides powerful tag management benefits:

  • Centralized Management: Control all tracking from one interface
  • No Code Deploys: Add/modify tags without republishing
  • Version Control: Track changes and roll back if needed
  • Preview Mode: Test tags before publishing
  • Advanced Triggers: Fire tags based on complex conditions
  • Ecommerce Support: Track Commerce transactions
  • Cross-platform: Consistent tracking across all pages

Prerequisites

Before implementing GTM on Squarespace:

  1. GTM Account: Create a free account at tagmanager.google.com
  2. Container: Create a Web container for your site
  3. Squarespace Plan: Business plan or higher (required for code injection)
  4. Admin Access: Full access to Squarespace site settings

Installation Methods

Available on Business plans and higher.

Step 1: Get GTM Container Code

  1. Log in to Google Tag Manager
  2. Click on your container ID (e.g., GTM-XXXXXX)
  3. Copy both code snippets provided

Step 2: Add to Squarespace

  1. In Squarespace, go to Settings > Advanced > Code Injection
  2. Paste the first GTM snippet in the Header section:
<!-- 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. Paste the second GTM snippet in the Footer section:
<!-- 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) -->
  1. Replace GTM-XXXXXX with your actual container ID
  2. Click Save

Method 2: Page-specific Injection

For specific pages or blog posts:

  1. Edit the page or post
  2. Go to Settings > Advanced
  3. Add GTM code to Page Header Code Injection
  4. Note: This approach is less ideal as it won't track all pages

Method 3: Template-level Implementation

For developers with custom templates:

  1. Download your template via Design > Custom CSS > Manage Custom Files
  2. Edit the template's header and footer files
  3. Add GTM snippets in appropriate locations
  4. Re-upload the modified template

Data Layer Implementation

Basic Data Layer Setup

Add this before the GTM container code in Header Code Injection:

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

// Page-level data
dataLayer.push({
  'pageType': '{.section collection}{collection.typeName}{.end}{.section item}{.if item.categories}{item.categories.0.title}{.or}blog{.end}{.end}',
  'pageTitle': document.title,
  'pageUrl': window.location.href
});
</script>

Product Page Data Layer

For Squarespace Commerce product pages:

<script>
{.section item}
  {.section productType}
    dataLayer.push({
      'event': 'productView',
      'ecommerce': {
        'detail': {
          'products': [{
            'id': '{id}',
            'name': '{title|json-prettify}',
            'price': '{structuredContent.variants.0.priceMoney.value}',
            'category': '{categories.0.title|json-prettify}'
          }]
        }
      }
    });
  {.end}
{.end}
</script>

Add to Cart Event

Squarespace Commerce fires events you can capture:

<script>
document.addEventListener('DOMContentLoaded', function() {
  // Listen for add to cart
  var addToCartButtons = document.querySelectorAll('[data-item-id]');

  addToCartButtons.forEach(function(button) {
    button.addEventListener('click', function() {
      dataLayer.push({
        'event': 'addToCart',
        'ecommerce': {
          'add': {
            'products': [{
              'id': button.getAttribute('data-item-id'),
              'name': button.closest('.product-block').querySelector('.product-title').textContent,
              'quantity': 1
            }]
          }
        }
      });
    });
  });
});
</script>

Commerce Transaction Tracking

Add to the order confirmation page code injection:

<script>
{.section websiteSettings.storeSettings}
  {.section order}
    dataLayer.push({
      'event': 'purchase',
      'ecommerce': {
        'purchase': {
          'actionField': {
            'id': '{orderId}',
            'revenue': '{grandTotal.value}',
            'tax': '{taxTotal.value}',
            'shipping': '{shippingTotal.value}'
          },
          'products': [
            {.repeated section lineItems}
            {
              'id': '{id}',
              'name': '{title|json-prettify}',
              'price': '{unitPricePaid.value}',
              'quantity': {quantity}
            }{.alternates with},
            {.end}
          ]
        }
      }
    });
  {.end}
{.end}
</script>

Common GTM Tags for Squarespace

Google Analytics 4 Tag

  1. Create a new GA4 Configuration tag
  2. Enter your Measurement ID (G-XXXXXXXXXX)
  3. Set trigger to All Pages
  4. Enable Enhanced Measurement in GA4

Facebook Pixel Tag

  1. Create Custom HTML tag
  2. Paste Meta Pixel base code
  3. Trigger on All Pages
  4. Add conversion events as separate tags
  1. Create Google Ads Conversion Tracking tag
  2. Enter Conversion ID and Label
  3. Trigger on purchase event
  4. Use revenue variable for conversion value

Common Triggers

Page View Triggers

Trigger Name Type Conditions
All Pages Page View All pages
Homepage Page View Page Path equals /
Product Pages Page View Page URL contains /shop/p/
Blog Posts Page View Page URL contains /blog/
Cart Page Page View Page Path equals /cart
Checkout Page View Page URL contains /checkout

Event Triggers

Trigger Name Type Conditions
Add to Cart Custom Event Event equals addToCart
Purchase Complete Custom Event Event equals purchase
Form Submit Form Submission All forms or specific forms
Outbound Links Click - All Elements Click URL does not contain hostname

Built-in Variables

Enable these GTM variables for Squarespace:

  • Page URL
  • Page Hostname
  • Page Path
  • Referrer
  • Click Element
  • Click Classes
  • Click ID
  • Click URL
  • Click Text
  • Form Element
  • Form ID
  • Form Classes

Custom Variables

Page Type Variable

Type: JavaScript Variable

function() {
  // Detect Squarespace page type
  if (window.location.pathname === '/') return 'homepage';
  if (window.location.pathname.includes('/shop/p/')) return 'product';
  if (window.location.pathname.includes('/blog/')) return 'blog';
  if (window.location.pathname.includes('/cart')) return 'cart';
  if (window.location.pathname.includes('/checkout')) return 'checkout';
  return 'other';
}

Product Price Variable

Type: Data Layer Variable Variable Name: ecommerce.detail.products.0.price

Transaction Revenue Variable

Type: Data Layer Variable Variable Name: ecommerce.purchase.actionField.revenue

Form Tracking Setup

Basic Form Tracking

  1. Create a Form Submission trigger
  2. Choose specific forms or all forms
  3. Create a GA4 Event tag
  4. Set event name to form_submit
  5. Add form parameters

Newsletter Signup Tracking

<script>
document.addEventListener('DOMContentLoaded', function() {
  var newsletterForms = document.querySelectorAll('.newsletter-form');

  newsletterForms.forEach(function(form) {
    form.addEventListener('submit', function(e) {
      dataLayer.push({
        'event': 'newsletter_signup',
        'formLocation': window.location.pathname
      });
    });
  });
});
</script>

Commerce Tracking Configuration

Enable Ecommerce in GA4

  1. In GTM, go to your GA4 Configuration tag
  2. Enable ecommerce features
  3. Set currency to match your store currency
  4. Configure ecommerce events

Required Commerce Events

Event Trigger Purpose
view_item Product page view Track product interest
add_to_cart Add to cart click Cart additions
begin_checkout Checkout start Checkout funnel
purchase Order confirmation Revenue tracking

Preview and Debug Mode

Using GTM Preview

  1. In GTM, click Preview
  2. Enter your Squarespace site URL
  3. Click Connect
  4. New window opens with Tag Assistant
  5. Navigate your site to test tags

Common Issues to Check

  • GTM container loads on all pages
  • Data layer variables populate correctly
  • Tags fire on appropriate triggers
  • No JavaScript errors in console
  • Ecommerce events include required data
  • Form submissions tracked properly

Debug with Browser Console

// View all data layer events
console.log(window.dataLayer);

// Monitor new events
dataLayer.push = function() {
  console.log('New GTM Event:', arguments);
  Array.prototype.push.apply(this, arguments);
};

Publishing Workflow

Pre-publish Checklist

  • Test all tags in Preview mode
  • Verify ecommerce tracking works
  • Check form submissions fire
  • Confirm conversion tracking
  • Review data in GA4 real-time reports
  • Test on mobile devices
  • Check page load performance

Publishing Steps

  1. Click Submit in GTM workspace
  2. Add version name (e.g., "Added GA4 ecommerce tracking")
  3. Write clear version description
  4. Click Publish
  5. Monitor for 24 hours

Version Control

  • Name versions descriptively
  • Document what changed and why
  • Note which tags were added/modified
  • Keep previous version accessible for rollback
  • Test major changes thoroughly before publishing

Troubleshooting

Issue Possible Cause Solution
GTM not loading Code in wrong location Verify Header/Footer injection
Tags not firing Incorrect triggers Check trigger configuration in Preview
Duplicate tracking Multiple GTM containers Remove redundant code
Ecommerce data missing Data layer not implemented Add Commerce tracking code
Forms not tracking Wrong form selector Update form trigger selectors
Purchase event not firing Confirmation page code missing Add to order confirmation
Revenue values incorrect Currency formatting Remove currency symbols
Tags fire on wrong pages Overly broad triggers Add URL/path conditions
Performance issues Too many tags Consolidate and optimize tags
AJAX not tracked Page doesn't reload Implement virtual pageviews

Advanced Configuration

Virtual Pageviews for AJAX

For single-page sections or AJAX navigation:

<script>
// Push virtual pageview
function trackVirtualPageview(pagePath) {
  dataLayer.push({
    'event': 'virtualPageview',
    'virtualPagePath': pagePath,
    'virtualPageTitle': document.title
  });
}

// Monitor URL changes
var lastPath = window.location.pathname;
setInterval(function() {
  if (window.location.pathname !== lastPath) {
    trackVirtualPageview(window.location.pathname);
    lastPath = window.location.pathname;
  }
}, 500);
</script>

Custom Dimensions

Pass custom data to analytics:

dataLayer.push({
  'dimension1': 'member_status',
  'dimension2': 'plan_type',
  'dimension3': 'content_category'
});

Track which links get clicked:

<script>
document.addEventListener('click', function(e) {
  var link = e.target.closest('a');
  if (link) {
    dataLayer.push({
      'event': 'link_click',
      'linkUrl': link.href,
      'linkText': link.textContent,
      'linkClass': link.className
    });
  }
});
</script>

Performance Optimization

Best Practices

  • Limit total tags to under 15-20
  • Use async loading for all tags
  • Minimize Custom HTML tags
  • Remove unused tags and triggers
  • Consolidate similar tags
  • Monitor page load impact

Load Time Testing

// Measure GTM impact
performance.mark('gtm-start');
// After GTM container loads
performance.mark('gtm-end');
performance.measure('gtm-duration', 'gtm-start', 'gtm-end');
console.log(performance.getEntriesByName('gtm-duration')[0].duration);

Squarespace-specific Considerations

Template Variations

Different templates may require adjustments:

  • Brine family: Standard implementation works
  • Bedford family: May need additional selectors
  • Avenue family: Check Commerce block structure
  • Custom templates: Test thoroughly

Squarespace Commerce Limitations

Be aware of these limitations:

  • Limited access to checkout pages (not Squarespace Commerce Advanced)
  • Some events must use JavaScript listeners
  • Currency formatting may vary
  • Digital products tracked differently

Member Areas

For member-only content:

{.section website.authenticatedAccount}
dataLayer.push({
  'memberStatus': 'logged-in',
  'memberSince': '{createdOn|date %Y-%m-%d}'
});
{.or}
dataLayer.push({
  'memberStatus': 'guest'
});
{.end}

Privacy and Compliance

GDPR Compliance

Implement consent before loading GTM:

<script>
// Check for consent cookie
if (document.cookie.indexOf('cookie_consent=granted') > -1) {
  // Load GTM container
  (function(w,d,s,l,i){...})(window,document,'script','dataLayer','GTM-XXXXXX');
}
</script>

Work with Squarespace's cookie banner:

  1. Configure cookie settings in Settings > Cookies & Visitor Data
  2. Adjust GTM loading based on consent
  3. Use GTM's built-in consent mode

Testing Checklist

  • GTM container loads on all pages
  • Data layer initializes before GTM
  • Product pages push product data
  • Add to cart events fire
  • Purchase tracking works on confirmation
  • Form submissions tracked
  • All configured tags fire successfully
  • No console errors
  • Mobile functionality verified
  • Page load performance acceptable

Additional Resources

// SYS.FOOTER