XorByte

Google Analytics not working with Gatsby.

May 02, 2020

Problem Scenario

I had been trying to figure out why Google Analytics wasn’t working on my Gatsby site since last 2 hours and i found the solution just now. Hereby i am posting the problem and the solution so that no other person on earth wastes time on this problem in future. This is the picture you want to see when you try to add google analytics for the first time.

google analytics

Common Solution for Gatsby

Without wasting any more time, here is the code which will make it work for you, if you are not a fool like me. Please install google analytics gatsby plugin via yarn or npm.

yarn add gatsby-plugin-google-analytics

or

npm install —save gatsby-plugin-google-analytics

In your gatsby-config.js, find the plugins array and add google analytics gatsby plugin as the first element.

You have to copy and paste from the first { to the last },

 plugins: [
          {
            resolve: `gatsby-plugin-google-analytics`,
            options: {
              trackingId: `UA-111111111-1`,
              head: true,
              anonymize: true,
            },
          },

Now you have to go to your Google Analytics accound and then copy the tracking ID from there and update the trackingId in the above code.

And this is it ! You shall have Google Analytics working !

Other issues

I am bit of privacy guy, so i had this DuckDuckGo privacy essentials extension added to my browser, which was blocking the google analytics tracking. I got to know this when i checked that the chrome browser which didn’t have this extension was being reflected in the traffic but the firefox traffic was not being shown in Analytics dashboard.

Make sure that there is no such privacy plugin which is blocking google analytics. Otherwise that traffic won’t show up in your analytics dashboard and you would either blame Gatsby or the plugin.

Ashish Kumar Singh , I am a Software Engineer, I 😍 Code. [Twitter] [Linkedin]