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.
- Create or log into your Google Analytics account.
- Configure your account and property information.
- Copy your global site tag. It should look like the following:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<your-google-track-id>"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '<your-google-track-id>');
</script>
Configure Google Analytics in Jekyll
The next step is to configure Google Analytics for your Jekyll site. To do this,
- Create a file named
analytics.htmlin the_includesdirectory. - Paste the Google Analytics Global site tag into the
analytics.htmlfile.- Copy your
<your-google-track-id>. - Open the
_config.ymlfile and add this line:
google_analytics: "<your-google-track-id>". - Back in the
analytics.htmlfile, replace<your-google-track-id>with this:{% raw %}{{ site.google_analytics }}{% endraw %}.
- Copy your
- Open the
default.htmlfile in the_layoutsdirectory. - Add the following lines above the closing
</head>tag:<head> ... {% raw %}{% if jekyll.environment == 'production' and site.google_analytics %} {% include analytics.html %} {% endif %}{% endraw %} </head> <body>
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