11th
January
2022
Add GTM to Gatsby using Helmet
One of my devs needed to add Google Tag Manager (GTM) to an older Gatsby project we built and he was running into issues implementing the GTM code provided by Google since the react-google-tag-manager package required a newer version of Gatsby and its dependencies.
The issue turned out to be that the strings needed to be escaped for Helmet/React to process it correctly. If you’re using an older version of Gatsby, the snippet below should help you add GTM and call your events as needed. Just add it to your main template file.
const googleAnalyticsId = 'your-google-id-here'
<Helmet>
<script async src={`https://www.googletagmanager.com/gtag/js?id=${googleAnalyticsId}`}></script>
<script>
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', "${googleAnalyticsId}");
`}
</script>
</Helmet>