Subscribe Watch on YouTube
All articles

Adding Google Analytics - Gatsby Site

Legacy note: this 2020 tutorial uses Universal Analytics and gatsby-plugin-google-analytics. Universal Analytics has been replaced by Google Analytics 4, and Gatsby’s own plugin page now recommends gatsby-plugin-google-gtag for gtag.js.

Google Analytics is an amazing tool that allows you to keep track of page visits, most popular pages, how people are finding your website as well as the location that they are visiting your website from. Adding Google Analytics to your Gatsby site will allow you to collect that data and more.

The first step in getting this setup is to create a Google Analytics account. Once you have created a property you will get a Tracking ID to add to your website. To add the Tracking ID to your website you will use gatsby-plugin-google-analytics. For a new Gatsby site, use gatsby-plugin-google-gtag instead.

You can get the plugin with the command

$yarn run gatsby-plugin-google-analytics

OR

$npm install --save gatsby-plugin-google-gtag

Next you are going to add the following snippet into your gatsby-config.js file.

{
    resolve: `gatsby-plugin-google-gtag`,
        options: {
            trackingIds: ['G-XXXXXXXXXX'],
            pluginConfig: {
                head: true,
            },
        },
},

Initially I was having some issues getting this to work. What I did to resolve this was to remove the unnecessary options given on the Gatsby instructions page and just use the snippet above. I also added this to the top of the plugins.

To test this do gatsby clean and then gatsby build && gatsby serve. Then go to your Google Analytics property and check real-time traffic. For a modern GA4 setup, use DebugView or the current debugging flow in Google Tag Manager instead of relying on the old Chrome extension workflow.

I hope this was helpful and solved any issues you were having with the gatsby google analytics plugin not working.

Found it useful? Share it.
Julia Pottinger

Written by

Julia Pottinger

Hi, I'm Julia. I've been in QA for over a decade. I spend my days testing software and my own time building apps and games, and I write here to share what I learn, the practical, honest lessons you can actually use.

Comments 0

Share your thoughts, ask questions, or add to the conversation.

Be kind and constructive. Stay on topic. No spam or self-promotion.
Loading comments…