How to set environment variables in Hugo

I was using Hugo for a recent website and wanted to only add the Google Analytics (GA) code if I was building for production. It took me way longer than I thought as in Jekyll it’s pretty straight forward.

1. Add GA tracking code to my config.yaml

googleAnalytics: "UA-123456"

2. Add GA to head within your index.html

Hugo includes a prebuilt internal template for Google Analytics tracking. So we use this and add it to the head tag within our main index.html.

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>{ { .Title } } - { { .Site.Title } }</title>
    <link rel="stylesheet" type="text/css" href="/css/styles.css">
    { { if eq (getenv "HUGO_ENV") "production" } }
        { { template "_internal/google_analytics.html" . } }
    { { end } }
    <h1>Hello World</h1>

We also wrap this in a conditional to check if we have set an enviormental variable HUGO_ENV to equal production

Note: Please excuse the gaps between the curly braces. I couldnt seem to get the correct syntax highlighting for golang templates working.

3. Build for production

Then you can build hugo for production by running this command which sets the HUGO_ENV variable to production

$ env HUGO_ENV="production" hugo

Hope this is helpful ✌️