TIL: How you can add goatcounter to your Hugo blog

In this TIL post, we will go over how you can add Goatcounter to your Hugo Blog. Goatcounter is an open-source privacy-friendly analytics tool, an alternative to Google Analytics.

Goatcounter Account This post assumes you have already created a Goatcounter account, more information here.

Luckily it is very easy to add Goatcounter to our blog. First, create a new partial HTML file. In my example, it will be at layouts/partial/analytics.html. However, you can call and place your file where ever you want, just remember it for later.

The contents of the file should look like this:

<script id="partials/analytics.html" 
  data-goatcounter="https://{{ .Site.Params.goatcounter }}.goatcounter.com/count"
  async src="//gc.zgo.at/count.js"></script>

We will see how to pass the goatcounter param, later on, the {{ .Site.Params.goatcounter }}

Next, go look for a file which is used as the template for all of our pages. In my case, it is located at layouts/_default/baseof.html and add the following just above your footer:

  {{- partialCached "header.html" . .Page -}}
  <main class="main {{- if (eq .Kind `page`) -}}{{- print " post" -}}{{- end -}}">
      {{- block "main" . }}{{ end }}
  {{- if .Site.Params.goatcounter }}
      {{ partial "analytics.html" . -}}
  {{- end}}
  {{ partial "footer.html" . -}}
  {{- partial "search.html" . -}}
  {{- block "body_end" . }}
File Names Note here the file location and name here {{ partial "analytics.html" . -}}, matches what I said above.

Finally, open your config.yml or config.toml and add the following. This is your site code on Goatcounter.

  # ...
  goatcounter: "haseebmajid"

You can find your site code in your settings > sites.


That’s it we’ve added Goatcounter to our Hugo blog.