Thumbnail image

How to Add Google Analytics to Your Jekyll Site

Why Adding Google Analytics?

Measuring the impact of your documentation is an important part of evaluating your documentation efforts. And one of the most useful metrics to take into account to measure documentation impact is the user engagement.

Google Analytics is one of the most popular and easy to use tools to implement and track websites traffic. And it’s fairly easy to implement into a static site, such as a Jekyll blog or documentation site.

Create a Google Analytics Account

If you have an active Google account, you can quickly get started with Google Analytics. Visit the Get started with Analytics page for more information.

  1. Create or log into your Google Analytics account.
  2. Configure your account and property information.
  3. Copy your global site tag. It should look like the following:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="<your-google-track-id>"></script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', '<your-google-track-id>');

Configure Google Analytics in Jekyll

The next step is to configure Google Analytics for your Jekyll site. To do this,

  1. Create a file named analytics.html in the _includes directory.
  2. Paste the Google Analytics Global site tag into the analytics.html file.
    1. Copy your <your-google-track-id>.
    2. Open the _config.yml file and add this line:
      google_analytics: "<your-google-track-id>".
    3. Back in the analytics.html file, replace <your-google-track-id> with this: {% raw %}{{ site.google_analytics }}{% endraw %}.
  3. Open the default.html file in the _layouts directory.
  4. Add the following lines above the closing </head> tag:
      {% raw %}{% if jekyll.environment == 'production' and site.google_analytics %}
      {% include analytics.html %}
      {% endif %}{% endraw %}

What these lines do is that whenever your Jekyll site is built in a production environment and there’s a google_analytics variable in the _config.yml file, it will render the analytics block in the analytics.html file to track your site activity with Google Analytics. 5. Make sure that whenever you run your build command for production, you specify it in a prefix, as such: JEKYLL_ENV=production bundle exec jekyll build