Hiya, I’m trying to get GrowthBook to send experim...
# ask-questions
b
Hiya, I’m trying to get GrowthBook to send experiment data to GA4 from a React app (create-react-app) on localhost, with GrowthBook also locally hosted. GA4 is seeing regular events but following the GB tutorial isn’t working, probably because I’m using Google Tag Manager and I guess it’s different? I used the recommended code in index.html:
Copy code
<head>
  <!-- Google dataLayer variables -->
  <script>
    window.dataLayer = window.dataLayer || [];
  </script>
  <!-- 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-xxxxxxxx');</script>
Copy code
<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>
Based on the GB tutorial I’ve put this in index.js:
Copy code
window.growthbook = new GrowthBook({
    apiHost: "<http://localhost:4100>",
    clientKey: "sdk-xxxxxx",
    enableDevMode: true,
    trackingCallback: (experiment, result) => {
        // TODO: Use your real analytics tracking system
        console.log("Viewed Experiment", {
            experimentId: experiment.key,
            variationId: result.key
        });
        // track using GA4
        if ("gtag" in window) {
            window.gtag("event", "experiment_viewed", {
                event_category: "experiment",
                experiment_id: experiment.key,
                variation_id: result.variationId,
            });
        } else {
            console.log("no gtag");
        }
    }
});
GrowthBook is working in the app; I created a feature in GrowthBook and can test for it in the app and display different UI 🙂 but the above always logs “no gtag”, and also it only runs once, on page load. Has anyone used GrowthBook with Google Tag Manager?
f
Hi Shelagh
We’re just working on documentation for GTM
@happy-autumn-40938 is working on that, he should be able to help
here is a preview (work in progress)
b
Thank you! I am out of the office tomorrow but will check this out on Friday 🙂
h
My initial guess is that the GrowthBook SDK is initializing and running before GA4 has loaded. You could debug this by using the developer tools / javascript console and typing
window.gtag
to see whether it's actually (eventually) defined.
Loading GA4 using GTM will cause some additional slowdown. You could also try loading GrowthBook in GTM, or perhaps moving GA4 out of GTM. Or you can use your GA4 loading code (in your GTM tag) to also trigger GrowthBook to instantiate.
b
@happy-autumn-40938 window.gtag is always undefined. My regular click events as defined in Google Tag Manager are appearing in the GA4 realtime report.
A possible typo in the doc; should “apiKey” be “apiHost”? Or have I missed something?
👀 1
Hiya, I think maybe we are talking about different things here, @happy-autumn-40938 @fresh-football-47124? What I can’t see is how to track the user action in an experiment, e.g. when they click a button in one variation or the other. My general tracking tabs are set up in GTM but I’m not sure I need to use GTM for integrating GrowthBook itself? window.gtag doesn’t seem to exist in GA4 in this situation, which is fine, but how do I tell GrowthBook when the user clicks a button? Shouldn’t there be an event? My events are either set up in GTM, e.g. for generic button click, or are custom events sent to dataLayer such as:
Copy code
window.dataLayer.push({
  event: 'login',
  userId,
});
f
you don’t have to add any additional tracking events globally for GrowthBook. GrowthBook can use your existing events from GA4. So if you have button clicks already tracked to GA4, in GrowthBook you would define a metric for that event, and define how to pull that event from the GA4 data.
b
Thank you! The code below in index.js works, but only the first time that I call :
Copy code
useFeatureIsOn('new-main-panel');
iin a component.
Copy code
const growthbook = new GrowthBook({
  apiHost: '<http://localhost:4100>',
  clientKey: 'sdk-xxxxxx',
  enableDevMode: true,
  trackingCallback: (experiment, result) => {
    console.log('Viewed Experiment', {
      experimentId: experiment.key,
      variationId: result.key,
    });

    // track using GA4
    window.dataLayer.push({
      event: 'experiment_viewed',
      event_category: 'experiment',
      experiment_id: experiment.key,
      variation_id: result.variationId,
    });
  },
});
1. I may have missed something, but gtag doesn’t seem to exist if you follow the latest GTM instructions. Instead, you have to use window.dataLayer.push to send the tracking event to GA4. Maybe that should be in the docs? 2. Is there a way to call trackingCallback again in a session - if the user logs out, and a different user logs in?
OK, I answered my own question; if I send an event to GA4 setting userId to null, then send a new one setting the new userId, that works 🙂 Just setting a new userId on top of the old one didn’t do it.
h
For #1, I added a note about this situation in the latest docs. Thanks for the heads up on this. https://docs.growthbook.io/guide/google-tag-manager-and-growthbook
In some situations,
gtag()
may never become defined. You can use your browser's developer tools / JavaScript console to confirm this by typing
window.tag
. If undefined, you may need to manually define it — either on your page or in a GTM custom HTML tag — using JavaScript. For example:
Copy code
window.gtag = window.gtag || function() { dataLayer.push(arguments); };
👍 1
b
By the way, I also needed to create the corresponding tag, trigger and dataLayer variables in GTM. Which is kind of obvious if you are familiar with GTM but for a dumb newb like me took a bit of figuring out…
a
@happy-autumn-40938 Thanks for the docs to implement it through GTM. I’ve a question, is it also possible to add the variant changes in Growthbook (like the js - using the UI interface)? So i’ve not update the code every time?
h
If you're talking about custom JavaScript injection via the SDK (and writing that JavaScript inside the GrowthBook app), that's not something we currently support. It is on our roadmap though.
1
a
thanks! Would be a nice feature 😄 I think there are many people who are looking for another tool because Google Optimize is sunsetting 😉
h
Absolutely. Our upcoming Visual Editor 2.0 (to be released soon) should help folks make a smooth migration. This will hopefully solve 90% of visual/front-end changes. After that lands, we'll look at JS injection as well.
🙌 1