[Common Issue] Using environment variables on Netlify correctly

answered
#1

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 $PATH and $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 netlify.toml.

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:

2 Likes
Handling API keys in a Proxy Redirect
#2

But how do we acutally used those evnironment variables inside the site.

#3

Hi @mittalyashu.

It seems like you’re asking about how to leverage environment variables throughout your source code, since I assume you read the above post, and understand that:

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.

dotenv (linked above) is a popular npm module that allows you to leverage environment variables in a project. It allows you to set secret variables and reference them in public code elsewhere, like connecting to a database for example:

# .env file in project root

DB_HOST=localhost
DB_USER=user
DB_PASS=password
// server.js file

require('dotenv').config()
const db = require('db')

db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})
#4

Yes, I am aware of that dotenv package.

But in order to use that package we have to define the .env file in the repository to use the defined variables, which means if the repository source code is public, then anyone can have access to the environment variables.

#5

I answered using .env on Netlify to be able to use dotenv on your build on SO, but here is the cross post:

WARNING: If this is a secret key, you will not want to expose this environment variable value in any bundle that gets returned to the client. It should only be used by your build scripts to be used to create your content during build.

Issue

dotenv-webpack expects there to be a .env file to load in your variables during the webpack build of your bundle. When the repository is checked out by Netlify, the .env does not exist because for good reason it is in .gitignore.

Solution

Store your API_KEY in the Netlify build environment variables and build the .env using a script prior to running the build command.

scripts/create-env.js

const fs = require('fs')
fs.writeFileSync('./.env', `API_KEY=${process.env.API_KEY}\n`)

Run the script as part of your build

node ./scripts/create-env.js && <your_existing_webpack_build_command>

Caveats & Recommendations

  • Do not use this method with a public facing repository if you are trying to hide the keys [open] because any PR or branch deploy could create a simple script into your code to expose the API_KEY
  • Only use the private keys for your build env. Public environment variables are safe to access inside your client code bundles.
  • The example script above is for simplicity so, make any script you use be able to error out with a code other than 0 so if the script fails the deploy will fail.
1 Like