Learn how to use Netlify's Deploy Context to only include Google Analytics in production in your GatsbyJS site.
2019-03-18
Earlier I shared how I use Netlify's Deploy Context to safely write drafts in GatsbyJS that never land in production.
Now I want to share another use of Netlify's Deploy Context to only include Google Analytics on a GatsbyJS site when it's in production. Using this solution guarantees Google Analytics tracking won't ever be included in a non-production preview environment without tribal knowledeg workarounds or hacks.
This solution requires that 1) you're building your site with GatsbyJS and 2) you're using Netlify for build/deploy/hosting.
It's a simple two step process:
gatsby-config.js
to only include the plugin in productionWith all things GatsbyJS, there's a plugin for Google Analytics and it's easy to setup.
From within your project, install gatsby-plugin-google-analytics
(the code below is using yarn
. You can install it with npm install --save
as well):
$ yarn add gatsby-plugin-google-analytics
Now, if you open your package.json
, you should see it in your list of dependencies
.
Since we want our analytics to be as accurate as possible, we're going to check that Netlify's deploy context is production
so the Google Analytics plugin is only included in production. (By default, this plugin checks for NODE_ENV === production
, so it won't include Analytics during gatsby develop
but gatsby build
sets NODE_ENV
to production
, so anything that's built and served will include it)
In the gatsby-config.js
, create an object called cfg
and set the file's module.exports
to that object:
const cfg = {
plugins: []
/* the rest of your config */
};
module.exports = cfg;
Now, between the cfg
definition and module.exports
, add a condition for when the CONTEXT
is production
that will creat a configuration for the Google Analytics plugin, followed by pushing the configuration to cfg.plugins
.
// cfg = {...}
if (process.env.CONTEXT === "production") {
const googleAnalyticsCfg = {
resolve: "gatsby-plugin-google-analytics",
options: {
trackingId: "UA-XXXXXXXXX-X" // <- your tracking ID
}
};
cfg.plugins.push(googleAnalyticsCfg);
}
// modules.exports = cfg;
To test, we're going to...
Now you know how to use Netlify's Deploy Context to bend GatsbyJS to your will (and keep your Google Analytics stats clean)!
Hey, I'm Chase. I help aspiring entrepreneurs and makers turn their ideas into digital products and apps.
Subscribe to my Newsletter
Every other week I publish the Curiously Crafted newsletter.
In it, I explore the intersection of curiosity and craft: the people who make stuff, what they make and the way they pursue the craft of making.