Does Google Analytics Track Localhost Activity?

Answer: Yes. It does.

Why should I care?

The other day I noticed that Google Analytics records my visits, events, etc. even when I’m on localhost. Uh-oh.

This can skew your analytics data. For example, sometimes I’ll spend an hour working on one page. This throws off the Avg. Session Duration.

Fortunately, there’s an easy solution to this problem.

How can I stop GA from running on localhost?

Wrap your Google Analytics code inside this code block.

<script>
var host = window.location.hostname;
if(host != "localhost") {
	// your google analytics code goes here
}
</script>

What does that code block do?

It checks to make sure your browser’s window.location.hostname isn’t localhost. If you’re on localhost, it skips loading the Google Analytics code.

This means Google Analytics won’t run anymore on localhost!

Excellent gif

Need help with a project? We'd love to hop on board. Hire Us.

Get In
Touch

Must be a valid email address.