Disabling Analytics for Local Hugo

August 3, 2017
2 min. read

Hugo’s watching web server is great for creating pages. Tweak a little and see the browser refresh. (Unless you break things and then it is still just a manual browser refresh away from back to the good state, once your page is unbroken.)

As I was developing local pages, I happened to have my realtime Google Anaytics open. I noticed I was hitting it. When I look back at yesterday’s stats, I have 124 visits to a page I was working on, but hadn’t published yet. That isn’t good.

I would have assumed that it would be disabled if running locally. So I started searching around for the code that inserts the script, so I could disable similar to how Disqus is disabled locally. However, I couldn’t find this script anywhere.

After some web searching, it turns out that this is in an internal template, compiled with hugo. I didn’t know that was a thing. Something to look out for when researching other template changes.

To find where this exists in your theme, look for {{ template "_internal/google_analytics.html" . }}. In the theme I am modifying for this site, it exists in partials/scripts.html. I’m not sure if this is common or not.

I created a new file named partials/google_analytics.html with the following code:

<!-- Disabled when running locally -->
{{ if not .Site.BuildDrafts }}
{{ if .Site.GoogleAnalytics }}
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
ga('create', '{{ .Site.GoogleAnalytics }}', 'auto');
ga('send', 'pageview');
{{ end }}
{{ end }}

Then I replaced {{ template "_internal/google_analytics.html" . }} with {{ partial "google_analytics.html" . }}.

Now running locally with the -D flag, the Google Analytics does not load and polute my real statistics. I typically run hugo -wD server in development.

Part 3 of 3 in the Hugo series.

Series Start | Implementing a Series in Hugo

comments powered by Disqus