Exclude Dev Traffic from Google Analytics

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) {
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

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

Hope this helps.

tutorial webdev