Google Analytics for Jekyll - Desired Persona
Desired Persona
Desired Persona
Desired Persona Subscribe
Affiliate marketer. Media buyer. Developer.
Updated 27 Feb 2017 · 1 min read

Google Analytics for Jekyll

Setup Google Analytics in less than five minutes.

What is Google Analytics?

Google Analytics tracking is a free web analytics service offered by Google that tracks and reports website traffic. It’s really easy to add the tracking code to your Jekyll static website.

Login to Google Analytics and create a new property to receive a Tracking ID for your website. You will find your Universal Analytics tracking code under Admin > Property > Tracking Info > Tracking Code.

Add Google Analytics tracking to all your website pages

Create a new file called analytics.html in the _includes folder found in your Jekyll website’s directory.

Paste the Google Analytics tracking code in to analytics.html and replace your Tracking ID with {{ site.google_analytics }}. When you have finished it should look like this.

 (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

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


Add Google Analytics Tracking ID to Jekyll’s _config.yml file

Now you need to reference your Tracking ID in your _config.yml file. Replace UA—XXXXXXXX-X with your own unique Tracking ID.

# Google services
google_analytics: UA—XXXXXXXX-X

Finally, open _includes/head.html and add the following code just before the end </head> tag. Google recommends this placement to track all of the pages on your website correctly.

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

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

So how do you get the analytics to only show up on a production environment?

NB: It’s worth mentioning that GitHub Pages is set to jekyll.environment == 'production' automatically so you’re good to go!

If you are using another hosting provider or building your site locally, you will need to prefix the build command with JEKYLL_ENV=production like so

JEKYLL_ENV=production bundle exec jekyll build

If you have followed all the steps correctly, you now have Google Analytics installed on your static website. You can double check your files in the _site folder when you build your site, to make sure your Google Analytics tracking code has been added before you push updates to your live static website.

Did you find this tutorial helpful?

Let me know by leaving a comment.

Jekyll Google Analytics
Desired Persona
Desired Persona Subscribe
Affiliate marketer. Media buyer. Developer.