There have been a few times that I've wanted to render something differently in development vs production while using Hugo. I've used hacks like $.Site.IsServer
before to see if I was running the development server, but that's not helpful if I want to see what the production site looks like when developing.
Checking the environment
It turns out Hugo has a couple of built-in ways of distinguishing between development and production environments. Unfortunately, the SEO for the Hugo documentation page that shows how to distinguish between them isn't great.
Here are two ways to find your environment in Hugo:
{{ hugo.Environment }} returns "development" or "production"
{{ hugo.IsProduction }} returns true or false
When you're developing locally with hugo server
, the environment will be set to development
by default. When you run hugo
to build your site, the environment will be set to production
by default.
Conditional rendering based on the environment
To conditionally render markup based on the environment, you can use any of the following methods:
{{ if eq hugo.Environment "development" }}
I render when in development
{{ end }}
{{ if eq hugo.Environment "production" }}
I render when in production
{{ end }}
{{ if hugo.IsProduction }}
I render when in production
{{ end }}
{{ if not hugo.IsProduction }}
I render when <strong>not</strong> in production, which means
I would render if the environment were manually set to "test"
{{ end }}
Setting the environment manually
To set your site to production
while developing, start the development server using one of the following commands:
# short version
hugo server -e production
# long version
hugo server --environment production
You can also set the environment by using a system environment variable.
HUGO_ENVIRONMENT=production hugo server
Hugo requires environment variables that change its configuration to be prefixed with HUGO_
. You can read more about that in Hugo's environment variable documentation.
Finally, if you wanted to set your environment to something other than production
while building, you can do that using any of the methods below. In the following examples, we're setting the environment to development
, but you could set this to any value you want.
hugo -e development
hugo --environment development
HUGO_ENVIRONMENT=development hugo
Hopefully this helps you as you build your Hugo sites. Feel free to leave a like or comment if you enjoyed this post!