Replace Hugo's inbuilt Google Analytics template with Minimal Analytics (GA4)

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.

  1. 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 -}}
  1. 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,
};
  1. In your config.toml somewhere higher up e.g below the title = "" entry, add the GA tracking code. Replace G-XXXXXXXXXX with your own tracking code.
googleAnalytics = "G-XXXXXXXXXX"
  1. Call the template in the head.html file or just before the closing </body> tag (in baseof.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.

2 Likes

UPDATE. Hugo v0.120.0 deprecated googleAnalytics, so here is the updated code–

In step 1

{{- with site.Config.Services.GoogleAnalytics.ID }}
  {{- 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" . ) }}
  {{- $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 -}}

In step 3

[services]
  [services.googleAnalytics]
    ID = 'G-MEASUREMENT_ID'

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.