The preferred way to use environment variables in Netlify is to set them in our environment - be that in the Build Environment Variables configuration widget (on the site’s “Build & Deploy settings” page), or via netlify.toml. The latter is a bit more flexible as you can set different values for different contexts - e.g. staging uses a staging
$API_ENDPOINT and production uses a production one; the former is a bit more secure, since only people with access to the Netlify admin UI for your site can see them, rather than “anyone who can clone your repo!”
These variables are made available mostly in the build environment - if your build command were env, then you’d see them listed - in addition to
$NODE_VERSION and some other stuff Netlify sets automatically. However, depending on how your build pipeline works, the variables may or not be available once your buildcommand started. If your build command is
node -p "process.env" - that will show you what Node.js sees for environment variables - and that should show the same thing as
env shows (which is what the shell run by the build script sees). This generally works correctly automatically and you don’t have to do those experiments to prove that the variables were or weren’t set unless you are debugging new settings in
However, some of the build pipelines that folks use DON'T automatically import/inherit variables from the parent shells. This thread shows such an example. So - the best practice is not to necessarily use something like dotenv but instead, use a build process that appropriately passes those environment variables that we expose in the shell, into the build environment. How you do that is up to you and your tools.
So now you have the variables set and available to your build process, great! But, unless your build pipeline DOES something with the environment variable - it's not going to be much use in the code that gets published and served to the browser - which doesn't understand
$API_ENDPOINT - that's just a string to the browser and to our CDN. Only the build environment knows about and can use environment variables in most cases, since they are set in the shell during build, but your code is not served from the build environment - it is served without modification after build.
There are some specific other use cases that enable environment variables at browse time, such as:
- Using the branch name in a split test via injected snippets, so you can track performance via google analytics.
- Using special Gatsby environment variables or React environment variables which can also be available at browse time.
You can also check a full list of environment variables recognized by Netlify here. (Will be on docs soon)