Adrian Gray's Blog

Gatsby conditionally using Google Analytics only on a live site

September 30, 2017

TLDR; How to conditionally include GA only when domain name matches a string.

Gatsby has a module to add Google Analytics (GA) to a site with no fuss gatsby-plugin-google-analytics. It works great for the simple cases. It automagically only adds GA when the environment is set to production, so when you’re in development mode no extra views are sent to GA. Great!

But I always check my site both locally (using Python’s SimpleHTTPServer), and then I deploy to Firebase and check again that everything is OK. This sends spurious page views to GA, which bugs me. The simplest way I found around it is do a quick hack to the gatsby-plugin-google-analytic source code. Here’s the steps:

Add ‘react-ga’ to your packages if you don’t already have it.

    yarn add react-ga

If you have installed gatsby-plugin-google-analytics, remove it from your packages and rerun the package install.

Remove the plugin entry from gatsby-config.js, it should look something like:

    {
      resolve: `gatsby-plugin-google-analytics`,
      options: {
        trackingId: `UA-12345678-90`
      }
    },

Now create a gatsby-browser file in your main directory, and add the following (obviously, swap in your GA code, and domain name):

    import ReactGA from 'react-ga'

    const domain = 'foo.com'
    let id = 'NOPE'

    if (document.location.hostname.indexOf('drlingua.com') !== -1) {
      id = 'YOUR-GA-ID-HERE'
    }

    ReactGA.initialize(id)

    exports.onRouteUpdate = (state, page, pages) => {
      ReactGA.pageview(state.location.pathname)
    }

And that should be it. You can look at the code from anywhere othan than the production site and you should not send any extra GA page views, unless the domain string you entered is included in the host name of the site.

I know, this should probably be do as a PR for gatsby-plugin-google-analytics. I will if I get a minute…


Kyle MathewsWritten by Adrian Gray who lives and works in Sydney making kids HTML5 games and doing fun side projects. You should follow him on Twitter