Reviews. Information. Tutorials.

Adding Google Tag Manager and Google Analytics to a Gatsby site

Add Google Analytics tracking to your Gatsby site using Google Tag Manager and maintain separate production and staging environments.
May 22, 2020

This document covers the following:

  • Adding Google Tag Manager to your Gatsby site.
  • Adding Google Analytics to your Gatsby site, using Google Tag Manager.

    • A simple configuration to track all pageviews on a site.
  • Maintaining separate production and staging environments for Tag Manager + Analytics.

Table of Contents

Things to know before you begin

1. Configure Google Analytics

You need 2 Google Analytics properties: one for measuring the staging version of your site and one for the production version.

  1. Follow Get started with App + Web Analytics to learn how to create Analytics web properties.

    1. Create a staging property and note the Measurement ID. See Find your Measurement ID (App + Web properties) for help.
    2. Create a production property and note the Measurement ID.
  2. Optionally configure any of the Enhanced measurement features for your staging and production sites.

A Google Analytics App+Web property for an example site.
A Google Analytics App+Web property for an example site.

2. Configure Google Tag Manager

The Google Tag Manager Environments feature will be used to load different Google Tag Manager containers for separate staging and production versions of your site.

  1. In Google Tag Manager, Create a new account and container.
  2. Follow Define environments and create a new custom environment named Staging.

    • Note: The Live default environment will be used for your production site.

    A custom staging environment in Google Tag Manager.
    A custom staging environment in Google Tag Manager.

  3. Enable the built-in variable Environment Name .

    • Note: This variable returns the user-provided name of the current environment. For the built-in environments, it returns "Live", "Latest", or "Now Editing". In all other cases it returns an empty string.

    Enable the Environment Name variable in Google Tag Manager.
    Enable the Environment Name variable in Google Tag Manager.

  4. Create user-defined variables to reference Google Analytics Measurement IDs

    • Create a new variable named GA Measurement ID (Production) of type Constant and set the value of the variable to the Measurement ID for the production property you created in Google Analytics.
    • Create a new variable named GA Measurement ID (Staging) of type Constant and set the value of the variable to the Measurement ID for the staging property you created in Google Analytics.

    A user-defined variable to hold the Analytics Measurement ID for the staging environment.
    A user-defined variable to hold the Analytics Measurement ID for the staging environment.

  5. Create a user-defined variable to lookup Google Analytics Measurement IDs per environment

    • Create a new variable named GA Measurement ID (Environment Lookup) of type Lookup Table.
    • Set Input Variable to {{Environment Name}}.
    • Add an input row and set Input to Staging and Output to the {{GA Measurement ID (Staging)}} variable.
    • Click the Set Default Value checkbox and set the Default Value value to the {{GA Measurement ID (Production)}} variable.

    A user-defined variable to lookup Analytics Measurement ID based on the environment.
    A user-defined variable to lookup Analytics Measurement ID based on the environment.

  6. Add the Google Analytics App+Web Tag

    1. From the container workspace, click Tags > New.
    2. Click Tag Configuration and select Google Analytics: App + Web Configuration.
    3. Set the value of Measurement ID to the variable {{GA Measurement ID (Environment Lookup)}}.
    4. Select to trigger the tag on All Pages (or on the subset of pages you want to measure).
    5. Save and publish your tag configuration.

    The Google Analytics App+Web tag configuration in Google Tag Manager using a lookup table for the Measurement ID.
    The Google Analytics App+Web tag configuration in Google Tag Manager using a lookup table for the Measurement ID.

3. Configure Gatsby with Google Tag Manager

Install the Google Tag Manager plugin

  1. Install gatsby-plugin-google-tagmanager.
  2. Update your gatsby-config.js with the following:

    /**
    * The currently active environment.
    * This is used to set the corresponding Tag Manager environment config.
    */
    const activeEnv =
     process.env.GATSBY_ACTIVE_ENV || process.env.NODE_ENV || "development"
    console.log(`Using environment config: '${activeEnv}'`)
    
    // The Tag Manager Container ID.
    const gtmContainerId = "YOUR_GOOGLE_TAGMANAGER_ID"
    
    /**
    * Tag Manager Environment values to configure gatsby-plugin-google-tagmanager.
    * null values will cause the default (live/production) snippet to load.
    */
    const gtmEnv = {
     // If tag manager plugin is configured with includeInDevelopment set to
     // true then you should create a corresponding Development environment in
     // Tag Manager and replace the null values with the container environment
     // auth and preview values. Otherwise the production snippet will load.
     development: {
       gtmAuth: null,
       gtmPreview: null,
     },
    
     staging: {
       gtmAuth: "YOUR_GOOGLE_TAGMANAGER_STAGING_ENVIRONMENT_AUTH_STRING",
       gtmPreview: "YOUR_GOOGLE_TAGMANAGER_STAGING_ENVIRONMENT_PREVIEW_NAME",
     },
    
     // According to GTM docs you should use standard tag for prod so we'll set to null.
     production: {
       gtmAuth: null,
       gtmPreview: null,
     },
    }
    
    plugins: [
     {
       resolve: "gatsby-plugin-google-tagmanager",
       options: {
         id: gtmContainerId,
         includeInDevelopment: false,
    
         // GTM environment details.
         gtmAuth: gtmEnv[activeEnv].gtmAuth,
         gtmPreview: gtmEnv[activeEnv].gtmPreview,
       },
     },
    ]
  3. In your gatsby-config.js set the value of gtmContainerId to your container ID. Find the ID by visiting your Google Tag Manager and click Workspace. Near the top of the window, find your container ID, formatted as "GTM-XXXXXX".
  4. In your gatsby-config.js set the value of gtmEnv.staging.gtmAuth. To find the value, follow instructions to Get Snippet for the Staging environment. In the snippet preview find the &gtm_auth query parameter and use that value.
  5. In your gatsby-config.js set the value of gtmEnv.staging.gtmPreview. To find the value, follow instructions to Get Snippet for the Staging environment. In the snippet preview find the &gtm_preview query parameter and use that value. It usually follows the pattern env-X.

The Staging environment tag manager snippet. It has the values for gtmAuth and gtmPreview.
The Staging environment tag manager snippet. It has the values for gtmAuth and gtmPreview.

Environment behaviors

As described in Environment Variables:

  • When running gatsby develop or gatsby serve the environment is development.
  • When running gatsby build the environment is production.

Set the GATSBY_ACTIVE_ENV environment variable to explicitly force an environment. For example, to set staging as the active environment:

export GATSBY_ACTIVE_ENV=staging

Note: The main benefit of setting the environment is during build and deployment workflows, covered below.

Publish the Tag Manager container

It's important you publish the Tag Manager container for changes to take effect. See Publishing, versions, and approvals for details.

You need to publish and set the correct container version for each Tag Manager environment. The Live environment in Google Tag Manager corresponds to your production site. For example, if you make a change in Tag Manager that you want to apply to both your staging and production environments, publish your changes in Tag Manager and set the environment to Live. Then you will separately need to update the custom staging environment to the latest version by using the Publish To.. feature in the Environments section of Google Tag Manager (see Set Versions). Unfortunately, Google Tag Manager doesn't seem to allow publishing to multiple environments in one step.

Note: If an environment does not have any container published then when your site loads Google Tag Manager it may receive a 404 response.

4. (Optional) Set Environment in GitHub Actions workflows

If you've configured GitHub Actions workflows, for example to automatically Deploy a Gatsby site to Firebase Hosting, then you likely want the Google Tag Manager staging environment to load when building and deploying your staging site.

In GitHub Actions workflows you can do this by setting the GATSBY_ACTIVE_ENV environment variable as part of the workflow.

  1. Update the staging workflow YAML for your project to include GATSBY_ACTIVE_ENV:

    .github/workflows/staging.yml

    name: Staging Build and Deploy
    on:
     push:
       branches:
         - staging
    
    jobs:
     build-and-deploy:
       name: Build & Deploy
       runs-on: ubuntu-latest
       steps:
         - name: Checkout Repo
           uses: actions/checkout@master
         - name: Set up Node
           uses: actions/setup-node@v1
           with:
             node-version: "12.x"
         - name: Build Site
           run: |
             npm install
             npm run build
           env:
             GATSBY_ACTIVE_ENV: "staging"
         - name: Deploy to Firebase
           uses: w9jds/firebase-action@master
           with:
             args: deploy --only hosting:staging
           env:
             FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}
  2. Update the production workflow YAML for your project to include GATSBY_ACTIVE_ENV:

    .github/workflows/production.yml

    name: Production Build and Deploy
    on:
      push:
        branches:
          - master
    
    jobs:
      build-and-deploy:
        name: Build & Deploy
        runs-on: ubuntu-latest
        steps:
          - name: Checkout Repo
            uses: actions/checkout@master
          - name: Set up Node
            uses: actions/setup-node@v1
            with:
              node-version: "12.x"
          - name: Build Site
            run: |
              npm install
              npm run build
            env:
              GATSBY_ACTIVE_ENV: "production"
          - name: Deploy to Firebase
            uses: w9jds/firebase-action@master
            with:
              args: deploy --only hosting:production
            env:
              FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}
  3. Commit these changes and push them to your master and staging branches.

    • Note: Pushing the commit to add the workflows will itself cause the workflows to execute. You can see the output of the workflow execution in the Actions tab of your GitHub project.