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:
<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>
<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:
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?