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 Copy $ pwd /hugo $ cp themes/beautifulhugo/layouts/partials/head.html layouts/partials/. head.html (changed lines only) Copy - {{ template "_internal/google_analytics_async.html" . }} + {{- partial "analytics" . -}} Create /layouts/partials/analytics.html with the following content Copy {{ 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) Copy 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
[Read More]