Stupidly Important – GTM / gtag difference | + debuggin, logs, config vars and more!!*

Stupidly Important GTM / gtag difference.

Basic Setup, Network Panel, Find duplicate events, Not firing events, simple error logging

The error message "Uncaught ReferenceError: gtag is not defined" indicates that your code is trying to call the gtag function before it has been defined. This is happening because you're trying to send a purchase event using gtag inside your button click event listener, but you've only included Google Tag Manager (GTM) on your page, not the Global Site Tag (gtag.js).

Since you are using GTM, you would typically push an event to the dataLayer and then use GTM to handle that event and send the appropriate data to Google Analytics. If you want to use gtag directly on your page (without GTM), you would need to include the gtag.js library and configure it with your GA4 Measurement ID as you've done in your previous examples.

To fix this issue, you have two options:

Option 1: Push the event to the dataLayer (to work with GTM)



button.addEventListener('click', function() {
    // Start your countdown, etc.
    // ...
    // When ready to send the event
    window.dataLayer.push({
        'event': 'purchase',
        'transaction_id': 'T12345',
        'value': 6.66,
        'currency': 'USD',
        'items': [{
            'id': 'SKU123',
            'name': 'Widget',
            'category': 'Gadgets',
            'quantity': 1,
            'price': 6.66
        }]
    });
});

For this to work, you need to have a Tag in GTM set up to listen for dataLayer events named 'purchase' and configured to send the purchase event to Google Analytics.

Option 2: Include gtag.js and configure it If you want to continue using gtag directly in your HTML, you need to include and configure it. Here's how you would add it:



<script async src="https://www.googletagmanager.com/gtag/js?id=YOUR_GA4_MEASUREMENT_ID"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){ dataLayer.push(arguments); }
    gtag('js', new Date());
    gtag('config', 'YOUR_GA4_MEASUREMENT_ID', { 'send_page_view': false }); // Optionally set 'send_page_view' to false if you don't want a pageview on load
</script>

Replace YOUR_GA4_MEASUREMENT_ID with your actual GA4 Measurement ID.

You would add this code inside the <head> tag of your HTML, before the closing </head> tag. Then, your existing gtag('event', 'purchase', {...}) call should work properly.

 

 


 

Let's break down your questions one by one:

  1. Tag Configuration in GTM for 2 Stream IDs and GTM:

    • You'll configure one GA4 event tag in GTM.
    • Use the "Event Name" you wish to track (e.g., "purchase").
    • Use a Lookup Table variable to determine the correct Measurement ID based on the hostname or other criteria.
    • Under "Triggering", select the trigger that fires on your desired event.
    • In the tag settings, if you need to send the event to two separate GA4 properties, you can set up two fields in the "Fields to Set" with send_to and the respective Measurement IDs as values.
  2. Example of Initial Page View Count in GTM:

    • The initial page view is typically the first event sent to GA4, which happens automatically with a "Page View" trigger.
    • Set up a GA4 Configuration tag that fires on "All Pages" to track page views.
    • This tag will not require a "send_to" field unless you are specifically sending page views to multiple GA properties.
  3. If Using GTM with Stream IDs:

    • If you're using GTM, you don't need to include gtag.js for GA4 on your page. GTM will handle sending data to your GA4 properties.
    • If you choose to send data directly to GA4 properties without GTM, you'd include the gtag.js code snippet on your page for each Measurement ID.
  4. Correct Layout for Data Layer and Purchase Event for GTM:

    • The data layer should be set up to push the necessary ecommerce data before the GTM container code.
    • In GTM, configure an event tag to fire on a custom event (e.g., "ecommercePurchase") using the data layer values for transaction details.

Here are code examples for both methods:

Directly to Stream IDs:


<!-- Global site tag (gtag.js) for Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=STREAM_ID_1"></script>
<script async src="https://www.googletagmanager.com/gtag/js?id=STREAM_ID_2"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'STREAM_ID_1');
  gtag('config', 'STREAM_ID_2');
</script>

Through GTM:

  • Add a custom event trigger in GTM for the purchase event.
  • Create a GA4 Event tag with the "Event Name" set to "purchase", and set the "Fields to Set" for send_to with the two Measurement IDs.
  • Ensure the ecommerce data is pushed to the data layer before the GTM container snippet.

Initial Page View via GTM:


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

Send Purchase Event via GTM:

  • Configure the data layer object for the purchase.
  • Create a GA4 Event tag that fires on a custom trigger (e.g., "purchase").

Keep in mind the exact setup in GTM will depend on your specific use case, and it's important to test your configuration thoroughly to ensure data is being collected as expected.

 

GTM Preview

 

In Google Tag Manager (GTM) Preview mode, you are indeed able to see the details of the data being sent, including which Measurement IDs (i.e., stream IDs for GA4 properties) the events are being sent to. Here's how it works and how you can get more insight into the process:

  1. Data Layers:

    • GTM operates based on the data layer, a JavaScript object on your page that contains all the information you want to pass to GTM and on to various platforms like Google Analytics.
    • When you set up a tag in GTM, you tell it to use information from the data layer or other variables.
  2. Tag Configuration:

    • When you configure a tag in GTM for Google Analytics 4 (GA4), you specify the Measurement ID directly in the tag or use a variable that resolves to a Measurement ID.
    • GTM uses this information to send data to the specified GA4 property.
  3. Preview Mode:

    • When you enter Preview mode in GTM and trigger an event, GTM shows you a detailed breakdown of what happens when that event is triggered.
    • You can see which tags fired, which variables were used, and if you have set up the Measurement ID correctly, you will see which GA4 properties the event is sent to.
  4. Understanding What GTM Sends:

    • Tags Tab: This shows you which tags were triggered by the event.
    • Variables Tab: You can see the values of all variables at the time the event was triggered, which includes Measurement IDs if they are being used.
    • Data Layer Tab: This tab shows you the state of the data layer at the time of the event. You can see what values were pushed to the data layer and are available to GTM.
  5. GTM Debug Console:

    • Within the GTM Preview mode, there is a debug console at the bottom of the page when you are on your site with Preview mode active.
    • This console gives you real-time information about which events are being triggered, what data is in the data layer, and what tags are firing as a result.
  6. Google Analytics DebugView:

    • For an even deeper understanding of what data is sent to GA, you can use the DebugView feature within the GA4 interface.
    • DebugView shows you events being sent to your GA4 property in real-time. You can enable debug mode in your GA4 configuration tag to see more verbose information in DebugView.
  7. Network Requests:

    • For the technically inclined, you can open your browser's developer tools and inspect the network requests being sent to Google Analytics.
    • Filter the network requests by searching for 'google-analytics' or 'collect', and you can see the payload of each request, which includes the Measurement ID, events, and parameters being sent.

Remember, for privacy and security reasons, always ensure that any testing or debugging is done in a safe environment, especially if you are working with real user data.

Duplicate Events

 

Duplicate events in Google Analytics can skew your data and lead to inaccurate analyses. Here’s how you can troubleshoot and resolve duplicate events using the network panel, GTM Preview, and other methods:

  1. Network Panel:

    • Open Developer Tools in your browser (usually F12 or right-click and select "Inspect") and go to the "Network" tab.
    • Filter by "collect" to see only Google Analytics requests.
    • Look for requests that are identical or have the same event parameters being sent multiple times.
    • Check the "Initiator" column to see what script or action initiated the request. This can help you identify if it’s a code on the page or a GTM tag causing duplicates.
  2. GTM Preview Mode:

    • Enter Preview mode in GTM and trigger the event you’re interested in.
    • Observe which tags are firing when the event occurs. If a tag fires multiple times for a single event, investigate the trigger conditions.
    • Check the trigger configuration for potential issues, like multiple events that are too similar or triggers that are too broad.
  3. Google Analytics DebugView:

    • In GA4, use the DebugView to see incoming events in real-time.
    • If duplicates appear, it’s a sign that either the page itself or the GTM configuration is firing events more than once.
  4. Check Tag Configuration in GTM:

    • Review each tag associated with the event to ensure they are not set up to fire under similar conditions that may overlap.
    • Make sure that triggers are specific enough to fire only under the intended conditions.
  5. Check Trigger Conditions:

    • Ensure that triggers for the event are not too broad or overlapping with other triggers.
    • Use conditions within triggers to narrow down when they should fire, possibly by using click classes, IDs, or custom data layer variables.
  6. Audit GTM Tags and Triggers:

    • Conduct a full audit of your GTM container. Look for any tags that should not be in the container or that have been set up incorrectly.
    • Use GTM’s version control to see when the duplication may have started and to revert to previous versions if necessary.
  7. Use GTM’s Built-In Deduplication:

    • For certain triggers, like form submissions, GTM has built-in deduplication features you can enable.
  8. Check for Hardcoded Tags:

    • Sometimes, the duplication occurs because events are being sent via GTM and hardcoded tags on the page. Ensure that you don’t have both for the same event.
  9. Review Site Code:

    • If you have access to the site's source code, look for hardcoded analytics calls that may be causing the duplication.
  10. Tag Sequencing (Advanced):

    • If you need multiple tags to fire for a single trigger but want to control the order and deduplicate, you can use tag sequencing in GTM to specify which tag fires first and set up conditions for the firing of subsequent tags.

Once you identify the cause of the duplication, you can adjust your tag and trigger configurations accordingly to prevent the duplicates from firing. Remember to test your changes in a staging environment if possible before publishing them live.

 

Triggers Set Up to Fire Under Similar Conditions: When triggers in GTM are set up to respond to similar or overlapping conditions, it may lead to duplicate events. For example:

  1. Click Triggers:

    • If you have multiple click triggers listening for clicks on any element with a certain class, and you have nested elements with the same class, both triggers might fire.
    • A Click trigger set for All Elements and another for Just Links could both respond to a link click, causing a duplicate event.
  2. Page View Triggers:

    • A Page View trigger that fires on all pages and another that fires on a subset of those pages (like all pages with /blog in the URL) could overlap when visiting a blog page.
  3. Form Submission Triggers:

    • Multiple form submission triggers without specific form IDs or classes could lead to multiple events if you have more than one form on a page.
  4. Custom Event Triggers:

    • Custom event triggers that listen for the same event name in the data layer but do not have unique conditions might lead to duplicates.

Why Not Just Send the On-Page Tag Directly to the Stream ID: You might choose to send tags directly to a GA4 property if you want to bypass GTM, usually for simplicity or to avoid an additional layer of configuration. However, GTM offers several advantages:

  • Centralized Management: All tags are managed in one place, reducing the need for developer intervention every time a tag needs to change.
  • Flexibility: Easily change tracking without altering the code on the page.
  • Debugging Tools: GTM's preview and debugging tools offer a controlled way to test tag firing.
  • Version Control: GTM keeps a history of changes, so you can roll back to previous versions if something goes wrong.
  • Advanced Triggering Options: GTM provides options for trigger conditions, blocking triggers, and tag sequencing.

Setting GTM to Listen Correctly: To set GTM to correctly listen for on-page events:

  1. Use Data Layer Pushes: For custom events, push an event to the data layer when the action occurs. For example:

dataLayer.push({'event': 'signupComplete'});

Then create a Custom Event trigger in GTM that listens for signupComplete.

  1. Unique Trigger Conditions: When creating triggers, be as specific as possible. For example, use unique IDs or data attributes to differentiate between similar elements.
  2. Blocking Triggers: Use blocking triggers to prevent a tag from firing when certain conditions are met, which can be the inverse of your firing trigger conditions.
  3. Use Event Parameters: For click events, you can pass additional parameters like {{Click Classes}}, {{Click ID}}, or {{Click URL}} to ensure the trigger is listening for the exact event you're interested in.
  4. Consistent Naming: Use a consistent naming convention for custom events within your data layer pushes to avoid confusion and overlapping event names.

By setting up GTM to listen for specific, well-defined events, you can minimize the risk of duplicate event tracking. Remember to test thoroughly using GTM’s preview mode, which shows exactly what triggers are firing and why, and refine your triggers based on that feedback.

 

Tag NOT firing

 

When troubleshooting a tag that is not firing in Google Tag Manager (GTM), and if the configuration seems correct at first glance, there are several deeper checks and tools you can use to diagnose the issue. Here’s a step-by-step guide to help you pinpoint the problem:

1. Use GTM Preview Mode

The first step is to use GTM's Preview Mode, which provides a real-time debugging environment:

  • Activate Preview Mode on your GTM workspace and visit the site where the tag should fire.
  • Inspect the Events in the preview pane that pops up at the bottom of your browser. It shows all dataLayer events and the tags that fire (or don't fire) in response to them.
  • Check the Variables and Data Layer to ensure that all the variables your tag and triggers rely on have the expected values at the right times.

2. Review Trigger Configuration

Double-check the trigger conditions:

  • Ensure the Event Name matches exactly what is pushed to the data layer. Remember, GTM is case-sensitive.
  • Multiple Conditions: If the trigger has multiple conditions, verify that all are being met. Sometimes, one part of a complex trigger condition can prevent a tag from firing.

3. Check Blocking Rules

Sometimes tags are set up with blocking triggers or exceptions that might be overlooked:

  • Review any blocking triggers that might be associated with your tag. These can prevent a tag from firing even if the primary trigger conditions are met.

4. Conflict with Other Tags

Sometimes, other tags can interfere or modify the data layer in ways that affect subsequent tags:

  • Check for Tags that Modify Data: Other tags that modify the data layer or related variables before your tag fires could affect whether your conditions are met.

5. Network Issues or Ad Blockers

External factors such as network issues or browser extensions (like ad blockers) can prevent tags from firing:

  • Disable Ad Blockers: Ensure no browser extensions are blocking GTM or network requests to Google Analytics.
  • Check Browser Console: Open the developer console in your browser (usually F12) and look for errors when the page loads and when the event should fire.

6. GTM Error Logging

While GTM does not have a built-in error log for non-firing tags, you can manually check for issues:

  • Console Errors: Look for JavaScript errors in the browser console that might indicate problems with the GTM setup or conflicts with other scripts.

7. GTM Version Control

Check whether a recent change might have affected the tag:

  • Review Changes: Use GTM’s version history to see recent changes and consider rolling back to a previous version if a recent update coincides with the issue.

8. Consult the GTM Community or Support

If all else fails, consider reaching out:

  • Google Tag Manager Community: Other users may have faced similar issues and can offer solutions.
  • Google Support: If your account has support options, consider reaching out for help.

In your specific case where one tag fires and another doesn’t, despite both using the same trigger, it suggests there might be a subtle configuration error or a problem with how the tags are set up in relation to each other or the send_to parameter. Ensure that the send_to parameter includes both Measurement IDs correctly formatted, separated by commas without spaces.

Network panel inconsitencies

why am I seeing the 2nd streamiid load up in network panel but the first does not? could it be the initial configuration tag that is at fault? or the lookup table? those are things I would liek some sort of error reporting in GTM about – if it was on a page in JS there would be a warning I feel.

ChatGPT

ChatGPT

When one stream ID appears in the network panel but another does not, several factors might be at play, including the initial configuration tag, the lookup table setup, or other elements within your Google Tag Manager (GTM) setup. Here are steps to diagnose and potentially resolve the issue:

1. Check the Initial Configuration Tag

Ensure that the initial configuration tag for each GA4 property (each stream ID) is correctly set up:

  • Correct Stream IDs: Verify that the stream IDs are correct and active in your GA4 properties.
  • Firing Rules: Ensure that the tag is set to fire on all pages or the correct trigger conditions. It’s possible that the configuration tag for the first stream ID isn't firing due to restrictive trigger conditions.

2. Review the Lookup Table

If you’re using a lookup table to dynamically assign the stream IDs:

  • Accuracy of Entries: Double-check the accuracy of the lookup table entries. Ensure that there are no typos and that the correct stream ID is associated with the expected conditions (e.g., hostnames).
  • Default Value: Make sure a default value is set in the lookup table. This can act as a fallback and might help reveal if the lookup conditions aren’t met.
  • Test Each Entry: Use the GTM preview mode to simulate each condition in the lookup table to ensure it resolves to the correct stream ID.

3. Verify Tag Sequencing

If there are dependencies between tags:

  • Tag Sequencing: Ensure that if there's any dependency (e.g., a configuration tag must fire before an event tag), the sequencing is set correctly. Sometimes one tag must fire to set up the necessary conditions or variables for another.

4. Check for JavaScript Errors

Open the browser's developer console:

  • JavaScript Errors: Look for any errors that might prevent scripts from executing correctly. An error in one part of the JavaScript on the page can stop subsequent scripts from running, affecting tag firing.

5. Consider Network Conditions or Content Blockers

Sometimes external factors can prevent tags from firing:

  • Ad Blockers or Browser Extensions: Ensure that no browser extensions are blocking part of your GTM or GA scripts.
  • Network Issues: Verify there are no network policies or firewall settings that might be blocking some requests based on URL or domain patterns.

6. Use GTM Debugging Tools

GTM's built-in preview and debugging tools can be invaluable:

  • Preview Mode: Check the firing of each tag and the values of all variables used in triggers and tags.
  • Network Requests in Preview: Preview mode also allows you to see the network requests associated with each tag firing, which can help identify why a tag might not be sending data as expected.

7. Documentation and Logging

While GTM does not provide direct error logging for non-firing tags:

  • Implement Custom Logging: For critical implementations, consider adding custom JavaScript that logs to the console or to an external logging service when certain actions are taken, helping to trace the flow of data and identify where things might be going wrong.

8. Consult the Community or Support

If the issue remains unresolved:

  • Community Forums: Places like the Google Tag Manager Forum or Stack Overflow can be resources for advice from other users who might have faced similar issues.
  • Google Support: If available, reaching out to support might provide additional insights.

By systematically checking each of these areas, you should be able to pinpoint the reason why one stream ID is not appearing in your network traffic and resolve the issue accordingly.

 

Simple basic logging

 

Setting up custom logging from Google Tag Manager (GTM) to an external service like Google Sheets can be a powerful way to monitor and debug issues or track data processing in real time. Here’s a simple guide on how to set up such a system.

Step 1: Create a Google Sheets Document

  1. Create a new Google Sheet to store your log data.
  2. Label columns according to the data you want to log (e.g., Timestamp, Event, Data).

Step 2: Set Up Google Apps Script

  1. Open your Google Sheet.
  2. Click on Extensions > Apps Script.
  3. Delete any code in the script editor and replace it with the following script. This script will append data sent via a GET request to the sheet:

function doGet(e) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var rowData = [];
  rowData.push(new Date()); // Timestamp
  for (var paramName in e.parameters) {
    rowData.push(e.parameters[paramName]);
  }
  sheet.appendRow(rowData);
  return ContentService.createTextOutput(JSON.stringify({"status": "success"})).setMimeType(ContentService.MimeType.JSON);
}
  1. Save the script.
  2. Click on Deploy > New deployment.
  3. Select Who has access to the app as "Anyone".
  4. Click Deploy and authorize the script using your Google account.
  5. Copy the URL provided after the deployment. This is your endpoint to which GTM will send data.

Step 3: Configure Google Tag Manager

  1. Create a Custom Image Tag in GTM:

    • Tag Type: Custom Image Tag.

    • Image URL: The URL you copied from Apps Script, structured as follows to include query parameters that will be logged:

      
      https://script.google.com/macros/s/SCRIPT_ID/exec?param1={{Variable1}}¶m2={{Variable2}}
      

      Replace

      
      SCRIPT_ID
      

      with your actual script ID from the URL, and

      
      {{Variable1}}
      

      ,

      
      {{Variable2}}
      

      with GTM variables or static values you want to log.

  2. Set up a Trigger for this tag:

    • Choose the appropriate trigger conditions based on when you want this data logging to occur (e.g., All Pages, Form Submissions, Clicks).
  3. Save and Preview the tag to ensure it fires as expected.

Step 4: Test and Debug

  1. Use the Preview mode in GTM to test the tag.
  2. Ensure that entries appear in your Google Sheet after the tag fires.
  3. Adjust parameters and triggers as necessary based on your specific logging needs.

Considerations:

  • Security and Privacy: Be cautious about logging sensitive or personally identifiable information (PII). Ensure compliance with data privacy laws.
  • Performance: Keep in mind that logging every event might impact the performance of your website, especially if many events are logged or if network issues affect the connectivity to Google Apps Script.
  • Scalability: While Google Sheets is an easy way to start logging, consider more robust logging solutions like databases or dedicated logging services if your requirements grow.

This setup provides a simple way to log data from GTM to Google Sheets, which can be extremely helpful for debugging and monitoring your tags' behavior in a live environment.

 

Scroll to Top