23 Apr 2019

Jekyll with Google Analytics

Does your static page built with Jekyll need analytics? It's very easy to setup Google Analytics with Jekyll.

Today I decided to set up Google Analytics for this page. After about two hours of playing around I finally managed to get everything done. In this tutorial I will try to explain how I set up Google Analytics with Jekyll.

First, if you still haven’t, create a new account on the Google Analytics admin dashboard. In my case, I created a new account with two properties, one for local development builds, and one for hosted production site. When both properties are created copy the Tracking IDs, let’s assume for the purpose of this article, it’s UA-PRODXX-1 for production build property and UA-DEVXX-2 for development build property.

Open project’s _config.yml file and add these lines:

# Analytics
prod-analytics-id:  UA-PRODXX-1
dev-analytics-id:   UA-DEVXX-2

Within _includes directory create a new file named tracking.html with the following content:

{% if jekyll.environment == 'production' %}
{% assign analytics-id = site.prod-analytics-id %}
{% else %}
{% assign analytics-id = site.dev-analytics-id %}
{% endif %}
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', '{{analytics-id}}');

Now include tracking.html in your layout so it’ll be included in all your pages when Jekyll builds your project. Open up the default.html file located in the _layouts directory and right above the closing </body> tag add {% include tracking.html %}:

// _layouts/default.html
    {% include tracking.html %}

Now when you run jekyll serve you can see data is being sent to Google Analytics for development environment. If you want to track production environment, just prefix jekyll build with JEKYLL_ENV=production, so it looks like:

JEKYLL_ENV=production jekyll build

Now when you run index file from the _site directory within a browser, you’ll see that pages are being built with the Google Analytics tracking code for production build. Visit your Google Analytics dashboard and you will see that everything is tracked as it should be.

Good luck and happy tracking!