Exclude Dev Traffic From Google Analytics

• 1 min read

Google Analytics is a great free tool for tracking your website. To avoid compromising tracking data, it is important to not have tracking enabled while building, testing, or fixing things.

Excluding Google Analytics tracking is best done at render-time on the server. However, for static websites that don’t have a server component, the same thing can be done on the frontend using Javascript. Here’s how:

// Get the current hostname (ex: "localhost:8000" or "mydomain.com")
var host = window.location.host;

// Check if the host begins with "mydomain.com"
var isProduction = host.indexOf('mydomain.com') === 0;

// Run GA code if on production
if (isProduction) {
    (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','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'MY-TRACKING-CODE', 'auto');
    ga('send', 'pageview');
}

Hope this helps.

If you enjoyed this tutorial, please consider sponsoring my work on GitHub 🤗

Be the first to cheers
Now look what you've done 🌋
Stop clicking and run for your life! 😱
Uh oh, I don't think the system can't handle it! 🔥
Stop it, you're too kind 😄
Thanks for the love! ❤️
Thanks, glad you enjoyed it! Care to share?
Hacker News Reddit

×

Recommended Posts ✍🏻

See All »
• 3 min read
✨ HTML Share Buttons
Read Post »
• 8 min read
🚜 A Simple Web Scraper in Go
Read Post »
• 2 min read
👨🏼‍💻 Going Indie, Again
Read Post »