Add Google Tags to Your Hugo Static Web Site
Published: 2024-05-07 | Updated: 2024-05-16Adding Google’s Tag Manager connect code to your static Hugo site won’t take long. Here’s how to do it in 3 simple steps.
Add your Google Tag ID to your site’s config
Now we need to add Google’s code to your site’s config file. Somewhere in your hugo.yaml file (or hugo.toml or hugo.json), add the following and replace the GOOGLE_ID with your own site’s Google ID code.
services:
googleAnalytics:
ID: G-YOUR_CODE_HERE
Using these keys in your config is what allows Hugo’s config params functions to capture and replace the gtag id code in the snippet we’ll create next.
Create a Google Tag html snippet
Create a file and name it googleTags.html
. It’s intended to be included in your site’s layout as a partial, so store it under `layouts/partials'
<!-- Google tag partial (layouts/partials/googleTags.html) -->
{{ $code := site.Config.Services.GoogleAnalytics.ID }}
{{ if $code }}
<script async
src="https://www.googletagmanager.com/gtag/js?id={{ $code }}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', '{{ $code }}');
</script>
{{ end }}
The magic is in this line:
{{ $code := site.Config.Services.GoogleAnalytics.ID }}
It grabs the config info from the Hugo config file and stores it in the local variable, $code
. If the code doesn’t parse for any reason, the {{ if... }}
block is just skipped.
Add the above partial to your site’s <head>
tag
Edit either your baseof.html
or one of the partials it depends on to include the partial above. In my case. baseof.html
pulls in a partial layouts/partials/head.html
. I’ll edit this <head>
partial to load the gtag.js
script near the bottom of the file.
<!-- layouts/partials/head.html -->
...
{{ partial "partials/googleTags.html . }}
...
And there you have it. Everything’s all wired up. Here’s how it all flows through from config to render:
- Hugo’s config file has the code under the correct property hierarchy
- The
googleTags.html
template partial will use that code to render the gtag.js connect script. - The gtag.js script will be included on every page of the site
These three steps ensure every page can connect with Google to report events as they happen.
With these changes in place, do a quick check that all looks OK locally. If all looks good, push these changes to production. Then you can go to Google’s Tag Manager setup dashboard and verify the script is working as planned on their end.