Ivory Tower

September 23, 2021

Opinion

I wanted to start off by saying unlike my other blog posts (or maybe I should say more so) this blog reflects my direct opinions

Step 1 Create Account/Login

The first thing you need to do is create a google analytics account at analytics.google.com. If you already have an account you will want to get to create account page. In the bottom left hit the gear -> Create Account.

Step 2 Account Setup

Step 3 Web Setup

Assuming your site is already live you will want to hit the web icon and put in your URL and a name. Before you hit complete you want to hit that gear icon in the left. Because Gatsby is a single page application it doesn’t reload the entire page. Due to that you want to hit advance settings under page views and unselect Page changes based on browser history events. Then click save in the top right and Create stream. This will then popup a details page you want to keep open.

Step 4 Gatsby Config

The easiest way to get Google Analytics to work with Gatsby is the Gatsby Plugin Google GTag you will want to install that to your project with npm install gatsby-plugin-google-gtag or equivalent yarn command. After that you will want to go to your gatsby config and add this to your plugins section

      resolve: `gatsby-plugin-google-gtag`,
      options: {
        // You can add multiple tracking ids and a pageview event will be fired for all of them.
        trackingIds: [
          "<Your measurement id>", // Google Analytics / GA
        ],
        // This object is used for configuration specific to this plugin
        pluginConfig: {
          // Puts tracking script in the head instead of the body
          head: true,
          // Setting this parameter is also optional
          respectDNT: true,
          // Avoids sending pageview hits from custom paths
          exclude: ["/preview/**", "/do-not-track/me/too/"],
        },
      },
    },

Step 5 Testing!

Normally when you run gatsby develop it won’t track google analytics. So you need to instead build the app for production which is gatsby build and gatsby serve if you are running the default configuration that should be live at localhost:9000 now when you switch back to Google Analytics hit the x on the top right of the modal we left open. Then, you want to go to reports on the left and find the “View Realtime” section. That should show your app running locally. Then you’re ready to start getting some insights! Congrats!