This implementation is based on the following tutorial and comment.
We shall override the internal template configuration so that googleAnalytics
value is used by our custom template instead.
- Create a Google Analytics file
/layouts/_internal/google_analytics.html
└───layouts
└───_internal
google_analytics.html
Copy-paste the following code into it–
{{- with site.GoogleAnalytics }}
{{- if hugo.IsProduction }}
{{- $ga4 := resources.GetRemote "https://cdn.jsdelivr.net/npm/@minimal-analytics/ga4/dist/index.js" }}
{{- $track := resources.Get "js/track.js" }}
{{- $opts := dict "params" (dict "trackingId" site.GoogleAnalytics) }}
{{- $track = $track | js.Build $opts -}}
{{- $stats := slice $track $ga4 | resources.Concat "js/analytics.js" | minify | fingerprint }}
<script src="{{ $stats.RelPermalink }}" integrity="{{ $stats.Data.Integrity }}"></script>
{{- end }}
{{- end -}}
- Create the tracking file in
assets/js/track.js
.
assets
└───js
track.js
Copy-paste the code below into it–
import params from "@params";
window.minimalAnalytics = {
trackingId: params.trackingId,
autoTrack: true, // <-- init tracking
defineGlobal: true,
};
- In your
config.toml
somewhere higher up e.g below thetitle = ""
entry, add the GA tracking code. ReplaceG-XXXXXXXXXX
with your own tracking code.
googleAnalytics = "G-XXXXXXXXXX"
- Call the template in the
head.html
file or just before the closing</body>
tag (inbaseof.html
file) depending on your preference.
{{- template "_internal/google_analytics.html" . -}}
Confirm after some time if the Real Time section of your GA4 account is populating stats.