Getting GA4 Working on Hugo with Beautifulhugo and Mainroad

Migrating Google Analytics to GA4

* This page contains promotional content

Migrating a site built with Hugo to GA4

In my environment I use the Beautifulhugo and Mainroad themes, so the customization here is limited to those
Also, this assumes the GA4 code for Google Analytics has already been obtained, so I will skip the explanation of Google Analytics itself

Beautifulhugo

Copy head.html into the root folder and edit it

$ pwd
/hugo

$ cp themes/beautifulhugo/layouts/partials/head.html layouts/partials/.

head.html (changed lines only)

-    {{ template "_internal/google_analytics_async.html" . }}
+    {{- partial "analytics" . -}}

Create /layouts/partials/analytics.html with the following content

{{ if not .Site.IsServer }}
{{ with .Site.GoogleAnalytics }}
<!-- Global site tag (gtag.js) - Google Analytics 4-->
<script async src="https://www.googletagmanager.com/gtag/js?id={{ . }}"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', '{{ . }}');
</script>
{{ end }}
{{ end }}

Write the GA4 code into config.toml (changed lines only)

googleAnalytics = "G-XXXXXXXXXX"

Mainroad

In the mainroad theme at the time of writing, analytics is loaded in layout/_default/baseof.html, and looking at the code below it seems as though GA4 is already supported

{{- if not .Site.IsServer }}
		{{- if hasPrefix .Site.GoogleAnalytics "G-" }}
		{{ template "_internal/google_analytics.html" . }}
		{{- else }}
		{{ template "_internal/google_analytics_async.html" . }}
		{{- end }}
	{{- end }}

However, for some reason no data was received even after configuring GA4

The work is almost the same as for beautifulhugo above; the only difference is that the file that loads analytics is baseof.html instead of head.html

Edit inside the Google tag in baseof.html

{{- if not .Site.IsServer }}
-		{{- if hasPrefix .Site.GoogleAnalytics "G-" }}
-		{{ template "_internal/google_analytics.html" . }}
-		{{- else }}
-		{{ template "_internal/google_analytics_async.html" . }}
-		{{- end }}
+	{{- partial "analytics" . -}}
 	{{- end }}

Write the GA4 code into config.toml (changed lines only)

googleAnalytics = "G-XXXXXXXXXX"

Reference article

For this migration work I used the article below as a reference

See also