Customize Google Analytics in Hugo Website Customize Google Analytics in Hugo Website

Guide to replace google analytics.js with gtag.js in Hugo

Page content

If you are using Hugo as a static site generator tool and using google analytics for your website then you can customize the analytics script and replace the old google analytics script analytics.js with recommended new script gtag.js with just few changes.

Add property to config.toml

If you are already using google analytics for your website then this property should be there otherwise you can add.

googleAnalytics = "UA-123456789-1"  # Get this Tracking-ID from your google analytics account

You can create an account to register your website with Google Analytics if you don’t have one and get this Tracking-ID.

Create google_analytics.html Partial

Next, We are going to create a partial called google_analytics.html which is responsible for injecting google analytics script in your hugo blog pages. All you need to do is copy the below code snippet and save it under $hugo/layouts/partials/google_analytics.html.

{{- with .Site.GoogleAnalytics -}}
<!-- Global site tag (gtag.js) - Google Analytics -->
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', '{{ . }}');
<script async src="{{ . }}"></script>
{{- end -}}

Add google_analytics.html partial to baseof.html

Next, You need to add google_analytics.html partial to baseof.html file (or any other file which is responsible to generate <head></head> section of Hugo pages) as below:-

<!DOCTYPE html>

    	{{- if not .Site.IsServer }}
		    {{ partial "google_analytics.html" . }}
    	{{- end }}

This above code snippet add the google analytics script in your hugo pages when it is not running as local server.

Remove internal partial from baseof.html

Please note that most of the hugo themes use Hugo’s internal google analytics template _internal/google_analytics_async.html. If you come across below code snippet in baseof.html file (or any other file) then you can remove that since this is no longer required.

{{- if not .Site.IsServer }}
	{{ template "_internal/google_analytics_async.html" . }}
{{- end }}

That’s it. Congratulations. You have added custom google analytics script to your pages successfully.