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'

      <script async src={`${googleAnalyticsId}`}></script>
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
          gtag('config', "${googleAnalyticsId}");