Google Analytics Only in Prodution with Jekyll

For Jekyll sites, here's how I approach including the Google Analytics script in production, but not development.

Jekyll sets a variable for the environment, which is performed within the Jekyll module (/lib/jekyll.rb):

  ENV["JEKYLL_ENV"] || "development"

The code shows that by default Jekyll runs in the development environment, unless you set a JEKYLL_ENV environment variable in your shell prior to building the site. The environment value is then available within your liquid templates as 'jekyll.environment'.

So, to only include the Google Analytics code in production:

  • Create an include file containing your Google Analytics JavaScript. I name my file google_analytics.html.
  • In your layout file, or wherever you would normally place your Google Analytics script, add a conditional include:
{% if jekyll.environment == 'production' %}
{% include google_analytics.html %}
{% endif %}
  • Then specify your environment when building for production:
$ JEKYLL_ENV=production jekyll build

I use the above command within as part of my deploy script so that I can't forget to include the Google Analytics script.

That's it, nice and easy!

Nothing is different when building for development, just use the default build command.

$ jekyll build

Written by Alex Brinkman who lives and works in Denver, but plays in the mountains.