Environment variables are the backbone for configuring and securing Node.js based apps. With so many modern conventions and techniques, it's easy to forget the basics of how Node.js handles environment variables.
Having a clear understanding of how to use environment variables in Node.js can prevent unexpected issues and security risks.
In this guide I'll be covering some quick essential steps to help master the concept of using environment variables, including:
How Node.js loads environment variables.
How and when to use dotenv.
How to maximize environment flows using dotenv-flow.
How Node.js version 20 handles environment variables.
Launching tests with environment variable support.
This guide will provide a quick recap on how to use environment variables with confidence.
Let's get started.
Node.js Environment variables
Let's start by identifying the supported environments in Node.js.
development
production
test
It's encouraged to use these standard environments because introducing custom environments could introduce inconsistencies.
Setting a Node.js environment
To set the environment in Node.js, use the designated variable key NODE_ENV and define it before executing the node runtime.
Bash
1NODE_ENV=production node app.js
Any additional variables can also be added as needed.
Unfortunately most teams might not be using Node.js version 20 yet, which leads developers to find alternative solutions to load variables.
Different types of .env files
Over the years, additional .env files were used to add flexibility and base default values for different environments. Larger development teams will benefit the most but this has become a new standard in many ways.
Examples of different .env files.
.env
.env.local
.env.development.local
.env.development
.env.production.local
.env.production
.env.test
Here's a breakdown of the general use cases when working with multiple scopes of environment config files.
These files are typically placed in the root of an NPM project.
For example:
Project structure
Bash
1└── <project-root>
2 ├── app.js
3 ├── .env
4 ├── .env.local
5 ├── .env.production
6 ├── .env.test
7 └── package.json
Strategies for Development
This is a typical strategy for a local development environment setup.
✅ Commit:
.env
.env.development
❌ Ignore:
.env.local
.env.development.local
Use .env.local and .env.development.local for any secret key overrides. Never put secrets in .env or .env.development.
Strategies for Production
Here's the general usage for production environment config files.
Using config files in a strategic way can allow for certain base environment files to be checked in securely.
By not committing .env.local and .env.*.local files and strictly using them for local config settings, can offer some flexibility.
Here's an example of how you can omit them from your git repo.
.gitignore
Bash
1.env.local
2.env.*.local
General tip:
Using third party .env loaders
Now that we've analyzed some of the modern conventions for using different files, let's look at some of the third party packages that support file loading.
Setting the path config to an array of environment config files does not mean that the file has to exist, it will simply go through the list until it finds an available match.
Loading from scripts and CLI
The dotenv package also provides a way to preload variables from NPM scripts or command line using a flag and path conifg:
-r: Stands for required and loads dotenv.
dotenv_config_[path]: Sets the path option on dotenv config object.
This is usually the better option as it preloads variables and removes the environment config loading from inside your modules.
This resembles the direction that Node.js is heading with the --env-file concept.
Loading with dotenv-flow
If you're building an app where you want the full environment flow loading process, then dotenv-flow is a package that can handle multiple config files.
The dotenv-flow is another popular solution, which actually uses a complete flow lookup process to find files in a certain sequential order.
To intall dotenv-flow package, use:
Bash
1npm install dotenv-flow
The dotenv-flow is very similar to dotenv but with some added bonuses:
It automatically adds a flow sequence to handle multiple environments based on the NODE_ENV value.
It will use the first variable it finds as it goes through the sequence flow, allowing files earlier in the sequence to override variables later in the sequence.
dotenv-flow loading order
Here's the default flow order dotenv-flow uses to find variables.
process.env (command line)
.env.[NODE_ENV].local
.env.[NODE_ENV]
.env.local
.env
It conveniently loads local files first, such as .env.local and .env.*.local which can be used to override base config files.
For example, any defaults set in .env.development can be overriden using .env.development.local.
Loading dotenv-flow in modules
Add the dotenv-flow to the top of your modules.
Using the default empty config automatically creates the flow order.
The environment values set for process.env in development would be:
Bash
1DB_HOST: 'env'
2DB_PORT: 'env'
3DB_USER: 'env.local'
4DB_PASS: 'env.local'
5DB_NAME: 'env.development.local'
Starting dotenv-flow in production
Now let's run the app in production and it will show the following.
Bash
1npm run start
The .env.production.local can override and set local credentials to access the production resources like database.
Bash
1DB_HOST: 'env.production'
2DB_PORT: 'env.production'
3DB_USER: 'env.production.local'
4DB_PASS: 'env.production.local'
5DB_NAME: 'env.production.local'
Starting dotenv-flow in test
Lastly, let's run dotenv-flow using the test environment.
If you noticed, I used the --setupFiles flag to config with dotenv-flow to resolve the environment values:
jest with dotenv-flow
JSON
1{
2 "test": "jest --setupFiles dotenv-flow/config",
3 }
You could use the same approach with dotenv config setup for test environments.
jest with dontenv
JSON
1{
2 "test": "jest --setupFiles dotenv/config",
3 }
Now, the app can be tested using.
Bash
1npm run test
We should the see the following values in the process.env object.
Bash
1DB_HOST: 'env',
2DB_PORT: 'env',
3DB_USER: 'env',
4DB_PASS: 'env',
5DB_NAME: 'env.test'
One thing to note that when running test, it will not load the .env.local. The values will be resolved from the .env base values and .env.test overrides.
In Conclusion
So hopefully that was quick recap on how Node.js can support environment config files with multiple scopes.
These are just a few of the popular packages available to use. To me it's less about which package you choose and more about having a strategy to use with Node.js.
Here's a few key takeaways:
There's no need to use every file in this example, it's just to show what's possible but use which files make sense for your project.
Try to keep the .env loading out of your modules and use command line or script preloading if possible.
Use the built-in --env-file as an option if you're using Node.js >=20.
Try to keep .env files easy to manage and not bulky and complex.