Have Different Portions Of Code For Production And Development

Avoid Loading Adsense and Analytics when developing

Last modified:


When developing your website, you probably want to exclude some portions of code like Google Analytics or Adsense when running under hugo local server but have them in your final site.

Here are some alternatives to do it.

Detecting Hugo’s built-in server

This is the easiest way to prevent code from executing when running the local server.

When you run hugo server command, Hugo sets the boolean variable .Site.IsServer to true.

.Site.IsServer: a boolean to indicate if the site is being served with Hugo’s built-in server.

Run code only in production:

{{ if not .Site.IsServer }}
	{{ template "_internal/google_analytics_async.html" . }}
{{ end }}

Run code only in development:

{{ if .Site.IsServer }}
{{ end }}

Or both:

{{ if .Site.IsServer }}
    <!-- DEVELOPMENT -->
	{{"<!-- Googla analytics placeholder -->" | safeHTML}}
{{ else }}
    <!-- PRODUCTION -->
	{{ template "_internal/google_analytics_async.html" . }}
{{ end }}

Using environment variables

You can also set environment variables and read their value in Hugo’s templates with the function getenv:

getenv: Takes a string containing the name of the variable as input. Returns an empty string if the variable is not set, otherwise returns the value of the variable.

When running the server, first export HUGO_ENV=production or run it directly: HUGO_ENV=production hugo

Having in your templates:

{{ if eq (getenv "HUGO_ENV") "production" | or (eq .Site.Params.env "production")  }}
	{{ template "_internal/google_analytics_async.html" . }}
{{ end }}

This way you can use the environment variable in your code or also set a parameter in configuration.

Only in development:

{{ if ne (getenv "HUGO_ENV") "production"  }}
{{ partial "custom-stats.html" . }}


Marcelo Canina
I'm Marcelo Canina, a developer from Uruguay. I build websites and web-based applications from the ground up and share what I learn here.
comments powered by Disqus

How to detect if you are serving your website locally or building it for production in Hugo. Load code depending on the environment.

Clutter-free software concepts.
Translations English Español

Except as otherwise noted, the content of this page is licensed under CC BY-NC-ND 4.0 . Terms and Policy.

Powered by SimpleIT Hugo Theme