Hugo: Only log to Google Analytics when not serving site locally

Date: 2019-12-02 | hugo | google-analytics | development |

problem

I'm developing my Hugo site a lot so obviously I'm serving it and then hitting it on localhost a good amount. Google Analytics is reasonably good at deduping some of these hits, but many are still logged as if they came from a regular visitor. How can I prevent my Hugo site from logging visits to Google Analytics when I'm running my site locally?

solution

Hugo has a pretty nifty IsServer function that you can use to determine if the default hugo server (accesssed via hugo serve) is being used to serve the site. As most (really all) production sites should be running on a real server like NGINX or Apache (the built-in hugo server is not recommended for production traffic), we can use this function to determine whether we should log to Google Analytics or not.

How do we tell the Google Analytics not to log a visit? We don't have to, we can just decide whether to include the script in the page based on the return value of IsServer which means nothing will be logged in the first place.

Here's an example partial that you can plop into your site's <head> that will only include the Google Analytics tracking script if you aren't serving your site via hugo serve (how you'd normally develop):

{{ if not .Site.IsServer }}
    {{ with .Site.GoogleAnalytics }}
        <!-- Global site tag (gtag.js) - Google Analytics -->
        <script async src="https://www.googletagmanager.com/gtag/js?id={{.}}"></script>
        <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', '{{.}}');
        </script>
    {{ end }}
{{ end }}

Note that the included script isn't anything special, it's just the template code Google Analytics gives you to put in your site with your user-id parameterized using Hugo's default .Site.GoogleAnalytics site parameter.

did this help?

I regularly post about tech topics I run into. You can get a periodic email containing updates on new posts and things I've built by subscribing here.

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.