Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mchaker/c6a3c0dd13c1b2aacc6eddc0446423b0 to your computer and use it in GitHub Desktop.
Save mchaker/c6a3c0dd13c1b2aacc6eddc0446423b0 to your computer and use it in GitHub Desktop.
Google Analytics 4 (with Measurement ID) in Hugo

Google Analytics 4 in Hugo

Blog post with slightly more detail can be found here. If you want to just get to it, read on.

I (very) recently decided to reimplement GA in my site, and found that existing implementation in Hugo was not compatible with GA4's new Measurement ID. This is an easy way to drop your Measurement ID into your site. I'm not going to go into how to sign up for GA.

This implementation requires that you create a site parameter for analytics, create a partial, and call the partial. I tweaked the names of the parameters and files so they didn't collide with the built-in hugo code.

Place the GoogleAnalyicsID (Measurement ID) in config.toml within [params].

# Google Analytics 4
GoogleAnalyticsID = "G-00000XXXXX"

Create the partial, analytics-gtag-ga4.html, and place it in /layouts/partials. Code below.

Call the partial just after the <head> tag in /layouts/_default/baseof.html. (maybe in a theme folder)

<head>
  {{ if and (hugo.IsProduction) (.Site.Params.GoogleAnalyticsID) }}
  {{ partial "analytics-gtag-ga4.html" . }}
  {{ end }}
  ...
 </head>

That's it. It appears that this will be fixed in gohugo shortly, but for now this is a serviceable workaround.

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id={{ .Site.Params.GoogleAnalyticsID }}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '{{ .Site.Params.GoogleAnalyticsID }}');
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment