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.
An example 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:
- Use any env variable name and values you need. The example targets the Hugo static site generator which has a function
getenv
to retrieve the value.
- I have not tested how using
context.branch-deploy
affects targeting a custom branch, so be careful for overrides of those contexts.
- Any variables specified in the
netlify.toml
overwrite the environment variables entered into the browser console on the Netlify site.