By Firoz AnsariMay 26, 20192 min readComments (0)

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:

<!-- layouts\partials\analytics.html -->
{{ if not .Site.IsServer }}

  <script type="text/javascript">
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

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

{{ 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.

Copyright © 2021 Firoz Ansari.
All Rights Reserved.