DEV Community

loading...
Cover image for How to add Google Analytics to your Hugo site

How to add Google Analytics to your Hugo site

charly3pins profile image charly3pins Originally published at charly3pins.dev on ・2 min read

Google Analytics

First of all what you need is to obtain a Google Analytics tracking ID. For that you need to sign up at Google Analytics. Then, you need to create a tracking ID following the next steps:

  • Click on Admin button (on the bottom left corner).
  • Click on Create Account button.
  • After all the steps filled, click the Create button and accept the terms and conditions.

After the completion of these steps you will obtain your tracking ID. Copy it for add to your Hugo site later.

Hugo configuration

Now it's turn to add the tracking ID to your site.
The easiest way for do it is using the Hugo's internal template provided by Hugo. You just need to add a new variable called googleAnalytics with the tracking ID obtained from the previous step in your config.toml like:

googleAnalytics = "UA-123-45"
Enter fullscreen mode Exit fullscreen mode

The next step is to add the following snippet of code in your site:

{{ template "_internal/google_analytics.html" . }}
Enter fullscreen mode Exit fullscreen mode

You should search for the head partial template and add it inside the <head></head> tags.

Checking the integration

Before passing that to production you can test it running your site locally performing the next command:

hugo serve
Enter fullscreen mode Exit fullscreen mode

The default url on localhost is http://localhost:1313.

Open again or refresh Google Analytics on a different tab.

Check the dashboard and you should be able to see the number under the section Active Users right now as 1 like the picture below:
active-users

I hope it helped you and feel free to comment here or contact me on my social media for any comments, questions or suggestions.

Discussion (2)

Collapse
idarek profile image
Dariusz Więckiewicz

It's nice, that makers of Hugo (and other JamStack builders) provided easy way to add Google Analytics, however that's wrong approach. You migrating to Hugo to gain speed. Using Google Analytics original script will not give you speed. It will load an additional bulk to your website unnecessarily. Same like adding Google Ads to your website, that is simply killing it or using Disqus. It's like running a marathon, but before you start you shooting into your foot.

The best approach however is to just add your minimal analytics code to your header using minimalanalytics.com

Collapse
charly3pins profile image
charly3pins Author

@idarek thanks for sharing that! I completely agree with you and solutions like that are perfect to solve those issues.

Forem Open with the Forem app