How to exclude Google Analytics running under local Hugo

I recently added Google Analytics to my website, which gives me a traffic report on my site. I was checking my analytic reports last night, and I discovered that page views from my localhost on analytics report. This contaminated traffic report is not good news. Google Analytics should only capture page view on production instance only.

I am continually running hugo server while making changes or enhancing something on my site as many Hugo developers. This causing localhost traffics captured in Google Analytics. I somehow manage to remove Google Analytics snippet from my pages if instance running on my localhost to resolve this issue.

One way to achieve this is to check the value of window.location.hostname in JavaScript, if it’s localhost then exclude the Google Analytic script. Seems a bit hacky to me! But after some research, I learned about a Hugo object property .Site.IsServer which can tell if the code is running under hugo server or not. I can put my Google Analytic script exclusion logic using .Site.IsServer. This implementation looks more cleaner to me.

Here is the code snippet to exclude Google Analytics script when running on the local machine:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<!-- layouts\partials\analytics.html -->
{{ if not .Site.IsServer }}

  <script type="text/javascript">
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

    ga('create', '{{ .Site.Params.ga_api_key }}', 'auto');
    ga('send', 'pageview');
  </script>

{{ end }}

With the above change, Google Analytics code snippet is no more rendering in the web pages when I am runing my site on my local machine and snippet is only rendering when the site is deployed on the production instance. The change should keep my Google Analytics report nice and clean.