How to add Google Analytics to Jekyll
Intention
The intention of this article is to provide you an easy step by step guide on how to add Google Analytics to your jekyll website.
What is Google Analytics?
Google Analytics is a service offered by Google, which helps you to analyse
and understand your website traffic.
This helps you to understand your visitors (or customers) better.
If you do not want to know if your website is visited, you might not need an analytics provider. But chances are, that
your are interested in who is coming along.
Additionally you might use the broad variety of data gathered for improving your users experience, marketing insights
and maybe even your content.
Preparations
- Sign Up for the service at the Google Analytics Website
- Go to the administration page
- Select the account from the drop down menu in the account colum or create a new one if needed
- Select the property from the drop down menu in the property column or create a new one if needed
- In the property column, click on “Tracking Info” and then on “Tracking Code”
- Keep the page open as you will need to code snippet from there afterwards
Adding Analytics
- Create a new file
analytics.html
in your_includes
folder - Copy the code snippet from the page opened in “Preparations” and paste it into the file.
- In your main file (probably found as
_layouts/default.html
) add the following snippet to include your analytics file:<head> <!-- Your head content --> {% include analytics.html %} </head>
- Done!
Possible improvement!
If running your site locally you do not want to track that most likely.
This can be easily configured by wrapping the include statement in a condition.
Replace the snippet from above with the following one:
<head>
<!-- Your head content -->
{% if jekyll.environment == 'production' %}
{% include analytics.html %}
{% endif %}
</head>
Jekyll normally runs in development mode, not in production so the analytics snippet is not included.
In case your jekyll website is hosted on github, the environment variable will be set automatically to production for
the hosted site. For other hosters you may be required to set the environment variable accordingly.
If you want to enable production mode locally, you can use the following command for running jekyll instead
(as described in jekylls documentation):
JEKYLL_ENV=production jekyll serve
Conclusion
Setting up analytics for a jekyll website is quite easy in my opinion. Did this short “How to” help you?