October 22, 2020Adding Google Analytics to Gatsby using Google Tag Manager

There are several tutorials on using Google Analytics with Gatsby, but I didn't find a single one that's leveraging the new Data Streams feature for the "Google Analytics 4 Property" type that allows you to combine app and web analytics data. So after figuring out how to set it up, I thought I might as well document it here for others to find.

So this is how add Google Analytics to Gastby using Data Strams and Google Tag Manager:

  • Set up a new "Google Analytics 4 Property" in Google Analytics
  • In the property configuration, add a new "Data Stream" of the type "Web". Enter your website URL and a name.
  • This will give you a "Measurement ID" of the form "G-XXXXXXXXXX"
  • Create a new container in Google Tag Manager
  • Add a new tag to the Container using "Tag Configuration" and selecting the "Google Analytics: GA4 Configuration"
  • Enter the Measurement ID obtained from Google Analytics
  • Add a Trigger to the tag choosing the "Custom Event" trigger type
  • Enter "gatsby-route-change" as the event name
  • Save the trigger and the tag, publish the container
  • Install the gatsby-plugin-google-tagmanager plugin:
yarn add gatsby-plugin-google-tagmanager
  • Add the plugin configuration to the plugins section of gatsby-config.js:
    resolve: "gatsby-plugin-google-tagmanager",
    options: {
        id: "G-XXXXXXXXXX",
        includeInDevelopment: false,