Google Analytics for Jekyll

 

What is Google Analytics

Google Analytics is a freemium web analytics service offered by Google that tracks and reports website traffic. It allows you to get information about your websites visitors such as the devices or OS they were using and their location.

Get started on analytics.google.com

Follow Get started with Analytics - Analytics Help. The goal of setting up on analytics.google.com is to get the Tracking ID and tracking code snippet of your website.

Enabling Google Analytics

Set up Analytics tracking - Analytics Help tells the details of how to set up tracking by different ways, depending on whether you want to track a website, an app, or other Internet-connected device.

Since pages powered by jekyll are static websites, one must copy and paste the Analytics tracking code into the source code on every web page wishing to track.

First, create a file in the _includes directory called google-analytics.html that contains the tracking code snippet generated by Google Analytics:

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', '{{ site.google_analytics }}', 'auto');
  ga('send', 'pageview');

</script>

Then, add the following to your _config.yml and replace TRACKING_ID with the one from Google:

google_analytics: TRACKING_ID

Next, we need include this new analytics file in our default layout. In _includes/head.html, add

{% if jekyll.environment == 'production' and site.google_analytics %}
{% include google-analytics.html %}
{% endif %}

Now when you run jekyll serve, your Google Analytics tracking code will not render at all in any pages. This prevents visit from localhost:4000 or 127.0.0.1:4000 messing up your analytics because by default Jekyll’s environment is set to development.

To build your site and include the Google Analytics code we’ve included, you need to build it in production environment. Pass in JEKYLL_ENV=production when running jekyll build:

$ JEKYLL_ENV=production jekyll build

Verify the tracking code is working

Once you have successfully installed Analytics tracking, it may take up to 24 hours for data such as traffic referral information, user characteristics, and browsing information to appear in your reports. However, you can check your web tracking code setup immediately.

Further reading