Jekyll - How to NOT add Google Analytics when developing locally?

Whenever I was developing on my local environment (for this site), Google Analytics was tracking every time I went to my site. This is not ideal as I don't really want to count this.

How do you avoid Google Analytics tracking your Jekyll site when developing on a local Environment?

Using the site Jekyll Variable, check if the URL is localhost or not. If it is not localhost then add Google Analytics. If it is localhost then don't.

Example (in the head of my default main layout default.html):

{% if site.url != "http://localhost:4000"%}
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src=""></script>
      window.dataLayer = window.dataLayer || [];
      function gtag() {
      gtag("js", new Date());

      gtag("config", "UA-111111111-1");
{% endif %}

The way it works is the following:

In the head of your default layout (or wherever you put your Analytics code), add this {% if site.url != "http://localhost:4000"%} {% endif %} liquid if statement.

This checks if the site.url is not "http://localhost:4000". "http://localhost:4000" is the default development environment site.url in Jekyll. But just in case yours is different, make sure to replace it with the correct one.

If the site.url is NOT the local environment then add Google Analytics (Make sure you add your own Tracking code).

You can check if it works by inspecting element on your local environment, you should no longer see Google Analytics. But if you go on your live site, you should still see it.

Want to learn how to code and make money online? Check out CodingPhase (referral link)