Back to Guides
    integrationsintermediate30 minutesJan 3, 2025

    Google Tag Manager Integration Guide

    Set up Google Tag Manager to track custom events and send data to Cogny. No code deployments needed for event tracking changes.

    Google Tag Manager Integration Guide

    TL;DR

    Set up Google Tag Manager to track custom events and send data to Cogny without code deployments—enabling marketing teams to add tracking independently in minutes vs days.

    What you'll accomplish:

    • Configure GTM to track business-specific actions (trials, feature usage, form submissions)
    • Create triggers and variables for automated event firing
    • Send custom events to GA4 (which exports to BigQuery for Cogny AI analysis)
    • Test events in GTM preview mode before publishing live
    • Enable marketing team to add/modify tracking without developer dependencies

    Time required: 30 minutes | Difficulty: Intermediate | Prerequisites: Website with GTM container installed, GA4 property connected, basic GTM understanding

    Quick Start: In GTM, create a new Custom Event trigger → Configure GA4 Event tag → Test in Preview mode → Publish to production → Verify in GA4 DebugView.


    Related Resources

    Essential guides for comprehensive event tracking:


    Question

    How do I use Google Tag Manager to send data to Cogny for better AI insights?

    Answer

    Set up Google Tag Manager to track custom events. Send events to GA4 (which exports to BigQuery). Connect BigQuery to Cogny.

    AI analyzes your custom tracking to find optimization opportunities you'd never spot manually.

    Quick Tip: Test tags in GTM Preview mode before publishing—misconfigured tags can break tracking entirely. Always verify events appear in GA4 DebugView before going live.

    Why Use Google Tag Manager?

    GTM makes tracking easier. No code deployments needed. Marketing team can add tracking independently.

    Without GTM: Every tracking change requires:

    • Developer time
    • Code changes
    • Deployments
    • Testing
    • Waiting

    With GTM: Add tracking yourself. Test in preview mode. Publish instantly. No developer needed.

    What You'll Track

    After this guide:

    Custom events Business-specific actions (trial starts, feature usage, upgrades)

    Enhanced e-commerce Product views, cart actions, checkout steps, purchases

    Form interactions Newsletter signups, contact forms, lead captures

    Scroll tracking Content engagement depth

    Video tracking Play, pause, completion rates

    Outbound clicks Links to external sites, downloads


    Note: GTM is not required for basic GA4 tracking, but it enables faster iteration on event tracking without developer deployments. Start with direct GA4 implementation if you're just getting started.

    Prerequisites

    You need:

    1. Google Tag Manager account (free)
    2. GA4 property (connected to BigQuery)
    3. Website access (to add GTM container code)

    Step 1: Create GTM Container

    Go to tagmanager.google.com

    Click Create Account

    Account name: Your company name

    Container name: Your website domain (e.g., yoursite.com)

    Target platform: Web

    Click Create

    Accept Terms of Service.

    Time: 2 minutes


    Step 2: Install GTM Container Code

    GTM shows installation code.

    Two code snippets:

    Snippet 1: Goes 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 -->
    

    Snippet 2: Goes 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) -->
    

    Add to your website:

    If you use WordPress:

    • Install "Insert Headers and Footers" plugin
    • Paste snippet 1 in Header section
    • Paste snippet 2 in Body section

    If you have custom theme:

    • Edit header.php or main template
    • Add snippet 1 before </head>
    • Add snippet 2 after <body>

    Time: 5 minutes


    Step 3: Verify GTM Installation

    Go back to GTM.

    Click Preview (top right).

    Enter your website URL.

    Click Connect

    New window opens showing your site with GTM debug panel.

    Check:

    • "Container Loaded" event fires
    • Tags, triggers, variables shown in debug panel

    If working: ✅ GTM is installed correctly.

    If not: Double-check code placement, clear cache, try incognito mode.

    Time: 3 minutes


    Step 4: Add GA4 Configuration Tag

    In GTM workspace:

    Click TagsNew

    Tag name: GA4 - Configuration

    Tag Configuration: Google Analytics: GA4 Configuration

    Measurement ID: Your GA4 ID (format: G-XXXXXXXXXX)

    Find this in GA4: Admin → Data Streams → [Your Stream] → Measurement ID

    Triggering: All Pages

    Click Save

    Time: 3 minutes


    Step 5: Configure Built-in Variables

    Click Variables (left sidebar)

    Scroll to Built-In Variables section.

    Click Configure

    Select these useful variables:

    • ✅ Page URL
    • ✅ Page Path
    • ✅ Page Hostname
    • ✅ Referrer
    • ✅ Click Element
    • ✅ Click Text
    • ✅ Click URL
    • ✅ Form Element
    • ✅ Form Text
    • ✅ Video Percent
    • ✅ Video Status
    • ✅ Scroll Depth Threshold

    Click outside modal to save.

    Time: 2 minutes


    Step 6: Set Up DataLayer Variables

    What's dataLayer?

    JavaScript object that holds data for GTM.

    You push data to it:

    dataLayer.push({
      event: 'trial_start',
      userId: '12345',
      planType: 'pro'
    });
    

    GTM reads this data and sends to GA4.

    Create variables for common data:

    Click VariablesNew

    Variable name: DL - User ID

    Variable Type: Data Layer Variable

    Data Layer Variable Name: userId

    Click Save

    Repeat for common data points:

    • DL - Plan TypeplanType
    • DL - Trial DurationtrialDuration
    • DL - Transaction IDtransactionId
    • DL - Transaction ValuetransactionValue
    • DL - Product NameproductName
    • DL - Product IDproductId

    Time: 5 minutes


    Step 7: Track Custom Events

    Example: Trial Start Event

    Step 7A: Add dataLayer push to your code

    When user starts trial, add:

    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
      event: 'trial_start',
      userId: user.id,
      planType: 'pro',
      trialDuration: 14
    });
    

    Step 7B: Create trigger in GTM

    In GTM: TriggersNew

    Trigger name: Event - Trial Start

    Trigger Type: Custom Event

    Event name: trial_start

    Click Save

    Step 7C: Create tag in GTM

    In GTM: TagsNew

    Tag name: GA4 - Event - Trial Start

    Tag Configuration: Google Analytics: GA4 Event

    Configuration Tag: Select GA4 - Configuration

    Event Name: trial_start

    Event Parameters:

    Click Add Row for each parameter:

    Parameter NameValue
    user_id{{DL - User ID}}
    plan_type{{DL - Plan Type}}
    trial_duration{{DL - Trial Duration}}

    Triggering: Select Event - Trial Start

    Click Save

    Time: 5 minutes per event


    Step 8: Track E-commerce Events

    Example: Add to Cart

    In your code (when user adds to cart):

    dataLayer.push({
      event: 'add_to_cart',
      ecommerce: {
        currency: 'USD',
        value: 99.00,
        items: [{
          item_id: 'SKU_12345',
          item_name: 'Wireless Headphones',
          item_category: 'Electronics',
          price: 99.00,
          quantity: 1
        }]
      }
    });
    

    In GTM:

    Trigger: Custom Event → add_to_cart

    Tag: GA4 Event

    • Event Name: add_to_cart
    • Send E-commerce data: ✅ Enabled
    • No additional parameters needed (uses dataLayer ecommerce object automatically)

    Common e-commerce events to track:

    • view_item - Product page view
    • add_to_cart - Add item to cart
    • remove_from_cart - Remove from cart
    • view_cart - View cart page
    • begin_checkout - Start checkout
    • add_payment_info - Enter payment details
    • add_shipping_info - Enter shipping details
    • purchase - Complete purchase

    See our GA4 Event Tracking Guide for detailed event examples and best practices. For the most reliable tracking, consider adding Server-Side Tracking for critical conversion events.

    Time: 10 minutes for full e-commerce setup


    Step 9: Track Form Submissions

    Auto-track all forms:

    Create trigger:

    In GTM: TriggersNew

    Trigger name: Form Submission - All Forms

    Trigger Type: Form Submission

    This trigger fires on: All Forms

    Click Save

    Create tag:

    Tag name: GA4 - Event - Form Submit

    Tag Configuration: GA4 Event

    Event Name: form_submit

    Event Parameters:

    Parameter NameValue
    form_id{{Form ID}}
    form_text{{Form Text}}
    page_path{{Page Path}}

    Triggering: Form Submission - All Forms

    Time: 5 minutes


    Step 10: Track Scroll Depth

    See how far users scroll on pages.

    Create trigger:

    Trigger name: Scroll - 25%, 50%, 75%, 90%

    Trigger Type: Scroll Depth

    Vertical Scroll Depths: 25,50,75,90

    This trigger fires on: All Pages

    Click Save

    Create tag:

    Tag name: GA4 - Event - Scroll

    Tag Configuration: GA4 Event

    Event Name: scroll

    Event Parameters:

    Parameter NameValue
    scroll_depth{{Scroll Depth Threshold}}
    page_path{{Page Path}}

    Triggering: Scroll - 25%, 50%, 75%, 90%

    Why this matters: AI identifies which content keeps users engaged. Optimize content that performs well. Fix or remove content with high bounce.

    Time: 3 minutes


    Step 11: Track Video Engagement

    For YouTube videos embedded on your site:

    Enable built-in video trigger:

    In GTM: TriggersNew

    Trigger name: Video - All Engagement

    Trigger Type: YouTube Video

    Capture: All video events (Start, Pause, Complete, Progress)

    This trigger fires on: All Videos

    Create tag:

    Tag name: GA4 - Event - Video

    Tag Configuration: GA4 Event

    Event Name: video_{{Video Status}} (using variable)

    Event Parameters:

    Parameter NameValue
    video_url{{Video URL}}
    video_title{{Video Title}}
    video_percent{{Video Percent}}
    video_status{{Video Status}}

    Triggering: Video - All Engagement

    Time: 4 minutes


    Step 12: Track Outbound Links

    Track clicks to external sites.

    Create trigger:

    Trigger name: Click - Outbound Links

    Trigger Type: Click - All Elements

    This trigger fires on: Some Clicks

    Fire this trigger when:

    • Click URL does NOT contain {{Page Hostname}}
    • AND Click URL starts with http

    Click Save

    Create tag:

    Tag name: GA4 - Event - Outbound Click

    Tag Configuration: GA4 Event

    Event Name: outbound_click

    Event Parameters:

    Parameter NameValue
    link_url{{Click URL}}
    link_text{{Click Text}}
    outbound_domain{{Click URL}}

    Triggering: Click - Outbound Links

    Why this matters: See which external links users click. Identify exit points. Understand what content/tools users seek.

    Time: 4 minutes


    Step 13: Test Everything in Preview Mode

    Before publishing:

    Click Preview (top right)

    Enter your website URL → Connect

    Your site opens with GTM debug panel.

    Test each event:

    1. Perform action (e.g., submit form)
    2. Check debug panel for event
    3. Verify tag fired
    4. Check parameters are correct

    Common issues:

    • Tag not firing: Check trigger conditions
    • Missing parameters: Check variable names in dataLayer
    • Wrong values: Check variable configuration

    Use GA4 DebugView to verify events reach GA4:

    In GA4: Configure → DebugView

    Enable debug mode in GTM preview.

    Perform actions on your site.

    See events appear in real-time in DebugView.

    Time: 10 minutes


    Step 14: Publish GTM Container

    Everything working in preview?

    Click Submit (top right)

    Version Name: Initial Setup - Event Tracking

    Version Description:

    - Added GA4 configuration
    - Custom events: trial_start, form_submit, etc.
    - E-commerce tracking
    - Scroll depth
    - Video engagement
    - Outbound link tracking
    

    Click Publish

    Your tracking is now live.

    Time: 2 minutes


    Step 15: Verify Data in BigQuery

    Events flow: Website → GTM → GA4 → BigQuery

    Wait 24-48 hours for first BigQuery export.

    Go to console.cloud.google.com/bigquery

    Query your events:

    SELECT
      event_name,
      COUNT(*) as event_count,
      COUNT(DISTINCT user_pseudo_id) as unique_users
    FROM `project.analytics_XXXXXX.events_*`
    WHERE _TABLE_SUFFIX = FORMAT_DATE('%Y%m%d', CURRENT_DATE())
    GROUP BY event_name
    ORDER BY event_count DESC
    

    You should see all your custom events.

    Time: 5 minutes (next day)


    Step 16: Connect to Cogny

    If BigQuery already connected to Cogny, you're done.

    Cogny automatically discovers new events.

    If not connected yet, see BigQuery Connection Guide.

    Time: Already done if BigQuery is connected


    Advanced: Enhanced Conversion Tracking

    Track revenue with more context.

    Purchase event with full details:

    dataLayer.push({
      event: 'purchase',
      ecommerce: {
        transaction_id: 'T_12345',
        value: 199.00,
        tax: 16.00,
        shipping: 5.00,
        currency: 'USD',
        items: [{
          item_id: 'SKU_67890',
          item_name: 'Premium Plan',
          item_category: 'Subscription',
          item_variant: 'Annual',
          price: 199.00,
          quantity: 1
        }]
      },
      // Custom parameters
      userId: 'USER_12345',
      isFirstPurchase: true,
      acquisitionChannel: 'google_ads',
      customerLifetimeValue: 199.00
    });
    

    In GTM:

    Tag automatically sends:

    • Standard e-commerce data (transaction_id, value, items)
    • Custom parameters (userId, isFirstPurchase, etc.)

    AI uses all this context for better insights.


    Best Practices

    1. Consistent naming

    Use verb_noun format:

    • trial_start
    • video_complete
    • feature_enable
    • trialStarted
    • videoCompletedWatching

    2. Descriptive event parameters

    More context = better AI insights.

    // Good
    dataLayer.push({
      event: 'feature_used',
      feature_name: 'export_report',
      feature_category: 'reporting',
      user_plan: 'pro',
      days_since_signup: 7
    });
    
    // Too vague
    dataLayer.push({
      event: 'feature_used',
      name: 'export'
    });
    

    3. Use GTM's folder organization

    Organize tags by type:

    • 📁 GA4 - Configuration
    • 📁 GA4 - Events - Conversions
    • 📁 GA4 - Events - Engagement
    • 📁 GA4 - Events - E-commerce

    4. Document with tag notes

    Every tag should have description:

    "Tracks when users start free trial. Includes plan type and duration. Used for conversion tracking and cohort analysis."

    5. Version control

    Publish with descriptive version names.

    Never publish version called "Latest changes" or "Update"

    Use: "Added checkout funnel tracking - 2025-01-03"

    6. Test before publishing

    ALWAYS use Preview mode. NEVER publish untested tags. One broken tag can break all tracking.


    Common Issues

    "GTM container not loading"

    Check:

    1. Code snippet in <head>? (before any other tags)
    2. Correct GTM ID? (GTM-XXXXXX)
    3. No ad blockers? (test in incognito)
    4. No JavaScript errors? (check browser console)

    "Events firing but not appearing in GA4"

    Check:

    1. GA4 Measurement ID correct in GTM configuration tag?
    2. GA4 configuration tag firing on all pages?
    3. Event names match between GTM and GA4?
    4. Using DebugView in GA4 to see real-time events?

    "dataLayer push not working"

    Check:

    1. dataLayer initialized BEFORE push?
    2. Event name spelled correctly?
    3. Parameters passed as object, not separate arguments?
    // Wrong
    dataLayer.push('event', 'trial_start', 'userId', '123');
    
    // Right
    dataLayer.push({
      event: 'trial_start',
      userId: '123'
    });
    

    "Variables showing 'undefined'"

    Check:

    1. Variable name in GTM matches dataLayer key exactly (case-sensitive)
    2. dataLayer push happens BEFORE tag fires
    3. Variable type is correct (Data Layer Variable, not something else)

    "Tags firing multiple times"

    Common on Single Page Apps (React, Vue, etc.)

    Solution:

    • Use trigger filter: "Fire this trigger when Page Path changes"
    • Or: Use built-in History Change trigger
    • Or: Debounce dataLayer pushes in your code

    Pro Tips

    1. Use GTM for all third-party tags

    Move ALL tags to GTM:

    • Facebook Pixel
    • LinkedIn Insight
    • Hotjar
    • Intercom
    • Any tracking script

    Benefits:

    • Single place to manage all tags
    • Conditional loading (reduce page weight)
    • Easy testing with preview mode

    2. Set up error tracking

    Catch JavaScript errors:

    Trigger: Custom Event → gtm.error

    Tag: GA4 Event

    • Event Name: exception
    • Parameters:
      • description: {{Error Message}}
      • fatal: false

    3. Create a naming convention document

    Document all events and parameters.

    Share with team.

    Prevents inconsistencies:

    • ❌ One dev uses trial_start, another uses start_trial
    • ✅ Everyone uses same event names

    4. Use GTM workspaces for collaboration

    Multiple people editing container?

    Use Workspaces:

    • Each person creates a workspace
    • Work independently
    • Merge changes when ready

    5. Set up tag firing rules carefully

    Don't fire tags on every page if not needed.

    Example:

    • Purchase tag: Only fire on /order-confirmation page
    • Trial start: Only fire when dataLayer event occurs

    Reduces unnecessary requests.

    6. Monitor GTM in production

    Use GTM's built-in monitoring:

    Admin → Container → Activity

    See:

    • Who published what
    • When changes were made
    • What changed between versions

    If tracking breaks, rollback to previous version immediately.


    What You Can Do Now

    Immediate actions:

    1. Audit current tracking

      • Review what events you track
      • Identify gaps
      • Plan new tracking
    2. Implement conversion events

      • Trial starts
      • Purchases
      • Signups
      • Key feature usage
    3. Add engagement tracking

      • Scroll depth
      • Video views
      • Form interactions
      • Outbound clicks
    4. Test and verify

      • Use GTM Preview mode
      • Check GA4 DebugView
      • Verify data in BigQuery

    Next Steps

    Immediate actions:

    • Create tags for your top 5 conversion events
    • Test everything in Preview mode before publishing

    Advanced implementation:

    Need help? Contact support


    FAQ

    Q: Can I use GTM without GA4?

    Yes, but not recommended for Cogny integration.

    GTM can send data to many platforms. But for Cogny, the flow is: GTM → GA4 → BigQuery → Cogny.

    Q: Should I replace GA4 tag with GTM?

    Yes.

    Remove hardcoded GA4 tag from your site. Manage GA4 through GTM instead.

    Benefits:

    • Single tag manager
    • Easier to add custom events
    • Better testing

    Q: Can GTM slow down my site?

    Minimal impact if configured correctly.

    GTM loads asynchronously. Doesn't block page rendering.

    Tips to keep it fast:

    • Don't add 50+ tags
    • Use tag firing rules (don't fire everything on every page)
    • Load non-critical tags with delay triggers

    Q: What's the difference between GTM events and GA4 events?

    GTM event = dataLayer event (triggers tags in GTM) GA4 event = sent to GA4 for analysis

    Flow:

    1. Your code pushes to dataLayer
    2. GTM detects event
    3. GTM tag sends to GA4
    4. GA4 exports to BigQuery
    5. Cogny analyzes

    Q: Can I track events without developer help?

    For some events, yes:

    • Form submissions (auto-detected)
    • Outbound clicks (auto-detected)
    • Scroll depth (built-in trigger)
    • Video engagement (built-in for YouTube)

    For custom business events (trial start, upgrade, etc.), you need developer to add dataLayer pushes.

    But once dataLayer is set up, marketing can create tags in GTM independently.

    Q: How many events should I track?

    Start with 10-15 critical events.

    Too few: Not enough insight. Too many: Noisy data, hard to analyze.

    Focus on:

    • 3-5 conversion events
    • 5-7 engagement events
    • 2-3 e-commerce events

    Q: Can I import events from other tools?

    Yes, with custom GTM templates.

    GTM Community Gallery has templates for:

    • Segment
    • Amplitude
    • Mixpanel
    • Facebook Pixel
    • etc.

    But for Cogny, direct GA4 integration is recommended.

    Q: How do I track single-page apps (React, Vue, etc.)?

    Use History Change trigger:

    Trigger Type: History Change

    This fires when URL changes without full page reload.

    For React/Vue:

    1. Enable History Change trigger
    2. Make sure GTM initializes before your app
    3. Push dataLayer events at appropriate lifecycle hooks

    Ready to Track What Matters?

    Most teams track page views. Maybe some clicks.

    But the insights come from tracking:

    • Specific user journeys
    • Feature adoption patterns
    • Conversion micro-steps
    • Engagement depth

    GTM makes this easy. GA4 stores it. BigQuery provides unlimited analysis. Cogny's AI finds the patterns.

    Not set up yet?

    Schedule a demo and we'll help you identify the 10 events that will unlock the best AI insights for your business.


    About This Guide

    Written by the Cogny team—built by the founders who created AI optimization systems for Netflix, Zalando, and Momondo at Campanja, and scaled growth for Kry, Epidemic Sound, and Yubico through GrowthHackers.se.

    We've implemented GTM for hundreds of websites. This is the proven approach.

    Last Updated: January 3, 2025

    Ready to Get Started?

    See Cogny in Action

    Schedule a demo to see how AI can transform your marketing analytics and automate your growth optimization.

    Schedule Demo