For this tutorial I will be assuming you already have a Hugo site setup, and that you have a Google Analytics property with a tracking ID created.

Adding the tracking ID to your site

Open your config.toml file, and add a field for googleAnalytics at the top level. Set the value to a string containing the tracking ID.

baseurl = "/"
title = "Austin Repp"
theme = "ghostwriter"
googleAnalytics = "UA-999999999-6" # This is the added line

    mainSections = ["post"]
    intro = true
    headline = "Austin Repp"

Next we will add a Hugo internal template to get the Google Analytics code snippet to be inserted on each of the sites pages when loaded. This is the template we will add:

 {{ template "_internal/google_analytics.html" . }} 

Depending on your theme, you may already have this template added. If it’s not already added as part of your theme, you will want to add it to one of the html partials that is used on every page. In my case, that’s header.html. Add the internal template for Google Analytics to the <head> tag on this partial.

       {{ template "_internal/google_analytics.html" . }}


Now you can run your Hugo site on localhost, or push it to your domain to make sure it works. The first way to make sure it’s adding the tracking to each page is to press F12 to inspect the page HTML. You can open the <head> tag on any page, and look for a script containing javascript like the following:

var doNotTrack = false;
if (!doNotTrack) {
   (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
   ga('create', 'UA-999999999-6', 'auto');
   ga('send', 'pageview');

This script being present is a good sign that you added the template correctly, and that it’s running the necessary javascript to send a page hit to Google Analytics. You can also try running the site on your phone or another computer, and seeing if the Google Analytics shows an active user while you’re viewing the page. Active User = 1

And that’s it! That’s all the necessary setup. Now your Hugo site should track visitors directly to Google Analytics.