Add Google Analytics to Your Hugo Site
This tutorial is for setting up Google analytics v4 on your Hugo site. Previous versions of Google Analytics used Tracking ID rather than Measurement ID.
Prerequisites⌗
Before we get started, go to https://analytics.google.com/ and create an account (or use your Google account).
Sign-in to your account before proceeding.
Step 1. Generate the Measurement ID⌗
Click on “Start measuring” to get started.
Fill out the Account, Property, and About your business forms.
Completing the forms should take you to the Admin page and on the Data Streams tab.
Select “Web” as your platform, and enter your website URL. The Measurement ID should display now. Look for a G-
prefix.
Save the value for later.
Step 2. Add Google Analytics Internal Template⌗
Most themes should have the Google Analytics v4 internal template in their head.html
. You can move on to the next step if it does.
If your theme does not add the internal template, then you will need to overwrite your theme’s head.html
.
Avoid modifying the theme’s head.html
because it introduces complexity when updating the theme. We also do not want to introduce any errors to the theme.
In your Hugo project directory, create layout/partials/head.html
and copy the contents of your theme’s head.html
into your file. For example, you would copy themes/anubis/layouts/partials/head.html
if you’re using the Anubis theme.
Then paste the following to the end of the file
{{ template "_internal/google_analytics.html" . }}
Step 3. Add the Measurement ID to your configuration file⌗
Assuming a config.toml
setup, add this line to your file
googleAnalytics: G-MEASUREMENT_ID
or you can set an environment variable HUGO_GOOGLEANALYTICS = G-MEASUREMENT_ID
. Your website’s page source exposes the Measurement ID, so the choice does not matter.
Conclusion⌗
Setting up Google Analytics on your Hugo site is simple and quick. It should take no more than 10 minutes. And it’s an easy way to get insight and tracking for your website.
Your Reports snapshot will begin to fill up with data as soon as you start receiving traffic.
Here are other resources to help you get started with Google Analytics.
- http://cloudywithachanceofdevops.com/posts/2018/05/17/setting-up-google-analytics-on-hugo/
- https://gideonwolfe.com/posts/sysadmin/hugo/hugogoogleanalytics/
Thanks for reading! Let me know what you think of this post on Twitter.