Implementing Google Analytics in Hugo

Hello, says Hugo has integrated support for Google Analytics, but I can’t find how it’s implemented more than the following line in Template Variables

.Site.GoogleAnalytics A string representing your tracking code for Google Analytics as defined in the site configuration.

So I’m guessing you put a line in the config-file: googleanalytics = "TRACKINGCODE"
Then call on it with {{ .Site.GoogleAnalytics }}

If so maybe this could be manifested with an explanation somewhere in the documentation?

Currently, this feature is not documented. But a pull request already on the way to be merged. Look at this Github issue to find an explanation:

From the proposed doc updates by Darrel Herbst:

Hugo ships with prebuilt internal templates for Google Analytics tracking, including both synchronous and asynchronous tracking codes.

Configuring Google Analytics

Provide your tracking id in your configuration file, e.g. config.yaml.

googleAnalytics = "UA-123-45"


Include the internal template in your templates like so:

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

For async include the async template:

{{ template "_internal/google_analytics_async.html" . }}
1 Like

Thanks guys!


What’s the difference between the two?


1 Like

For those of us deploying our website from a public Github repository, is there a risk to having our Google Analytics Tracking ID displayed in our source code for congif.yaml? Is there some way to avoid this?

1 Like

In case someone sees this and has the same question: there is no risk to committing your GA tracking ID. Anyone can find it by inspecting the source code of your site. This is by design, otherwise it wouldn’t be able to track site visits.

The Google Analytics console has a domain verification process to prevent someone from using your tracking code on a separate site and messing with your analytics data.

With that said, it’s possible you could use environment variables to get around this but it will still be in your commit history.

1 Like