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