We're using Netlify's automatic deployment for all pushed git branches.
We want to include our analytics scripts (et al) only for the master branch, i.e. the version of the website that our users are visiting.
It's possible to build environment variables on Netlify, but I don't get if it's possible to differentiate variables for certain branches?
There is a way to setup environment variables based on the deploy context in Netlify in your netlify.toml
file. This is being used in a production site using Hugo, but you can use any keys you want for the variables and commands.
netlify.toml
# Global settings applied to the whole site.
[build]
command = "yarn build"
publish = "public"
# build a preview of the site (Drafts and Future dates also)
[context.deploy-preview]
command = "yarn build:preview"
[build.environment]
HUGO_ENV = "development"
[context.production.environment]
HUGO_VERSION = "0.29"
HUGO_ENV = "production"
# you can lock a version of hugo for a deploy preview
[context.deploy-preview.environment]
HUGO_VERSION = "0.29"
HUGO_ENV = "deploy" # TEST: should be deploy or something other than production
# you can lock a version of hugo for a branch-deploy (other than previews)
[context.branch-deploy.environment]
HUGO_VERSION = "0.30"
HUGO_ENV = "development"
Also target a specific branch (example: new-branch)
# build a preview of the site (Drafts and Future dates also)
[context.new-branch]
command = "yarn build:preview"
# you can also target a specific branch
[context.new-branch.environment]
HUGO_VERSION = "0.29"
HUGO_ENV = "deploy" # TEST: should be deploy or something other than production
Solution: Now there will be an environment variable called HUGO_ENV
that will have a value to know the context (production, development, deploy) defined. The build language can now access those variables to make decisions on what to include in the build results.
NOTE:
getenv
to retrieve the value.context.branch-deploy
affects targeting a custom branch, so be careful for overrides of those contexts.netlify.toml
overwrite the environment variables entered into the browser console on the Netlify site.