DEV Community

Cover image for How to add Google Analytics to your Hugo site
charly3pins
charly3pins

Posted on • Originally published at charly3pins.dev on

How to add Google Analytics to your Hugo site

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.

Top comments (2)

Collapse
 
charly3pins profile image
charly3pins

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