process core module of Node.js provides the env property which hosts all the environment variables that were set at the moment the process was started.
process does not need to be imported — it is a global object in Node.js.Setting environment variables at startup
The following command runsapp.js and sets USER_ID and USER_KEY:
USER_ID as 239482 and USER_KEY as foobar. This is suitable for testing; for production, you will probably be configuring bash scripts to export variables.
Here is an example that accesses those environment variables:
Loading variables from a .env file
Node.js 20 introduced experimental support for .env files.
Use the --env-file flag to specify an environment file when running your Node.js application.
app.js with environment variables loaded from the .env file:
.env file, making them available to the application via process.env.
Multiple .env files
You can pass multiple --env-file arguments. Subsequent files override pre-existing variables defined in previous files:
If the same variable is defined in both the environment and in the file, the value from the environment takes precedence.
Optional .env files
To avoid throwing an error if the .env file is missing, use the --env-file-if-exists flag:
Loading .env files programmatically with process.loadEnvFile()
Node.js provides a built-in API to load .env files directly from your code: process.loadEnvFile(path).
This method loads variables from a .env file into process.env, similar to how the --env-file flag works — but can be invoked programmatically.
Example
Given a.env file:
- ESM
- CJS
- ESM
- CJS