Load Configuration Into the Enviroment in Node.js

11 min read·Jan 13, 2026

When writing CLI tools, command-line flags are the best way to temporarily change the behavior of the program for a single execution, such as enabling verbose mode or selecting an output format.

However, CLI tools often also need a more persistent type of configuration and a safer way to store sensitive values, such as API keys, tokens, or secrets, without typing them on every command or leaking them into your shell history.

These values are usually stored in the shell environment, or in .env files whose contents are loaded and injected into the environment at startup.

📚 The shell environment, often abbreviated env, is a collection of variables in the form of name-value pairs.

For example:

HOME=/home/razvan/projects
PATH=/usr/bin:/bin:/usr/sbin:/sbin/
USER=razvan

Access environment variables

In Node.js, the environment variables available in the shell session the script was launched from are exposed through the global process.env object:

process.env.ENV_VAR

⚠️ While the process.env object can be modified by the script, such modifications won't be reflected outside of the Node.js process.

💡 It is usually recommended to provide fallback values in case environment variables are undefined.

Example

Let's consider this script, that re-implements the Unix printenv utility:

printenv.js
// Remove the first 2 elements of the `argv` array
const args = process.argv.slice(2);

// Check if there are positional arguments
if (args.length > 0) {
  // Retrieve the last positional argument
  const varName = args[args.length - 1];

  // Check if the variable exists in the `env` object
  if (varName in process.env) {
    // Output its value
    console.log(process.env[varName]);
  } else {
    // Terminate with an error
    return process.exitCode = 1;
  }
} else {
  // Loop on each key of the `env` object
  for (let key of Object.keys(process.env)) {
    // Output the key-value pair
    console.log(`${key}=${process.env[key]}`);
  }
}

// Terminate without errors
process.exitCode = 0;

Which will produce this output:

$ node printenv.js
SHELL=/bin/bash
USER=razvan
PWD=/Users/razvan/learnbackend/scripts/printenv.js
PS1=\u:\w$
SHLVL=1
HOME=/Users/razvan
$ node printenv.js USERNAME
$ node printenv.js SHELL
/bin/bash
$ node printenv.js SHELL USER
razvan

Store and load configuration using .env files

An .env file, also called a dotenv file, is a plain text file that allows developers to keep configuration and secrets outside of the code, and load them into the process environment when running a CLI tool.

💡 If often happens that .env.development or .env.production.

The .env file format

.env files store variables as key-value pairs, where each pair is represented by a variable name followed by the equal sign (=) followed by a variable value.

VARIABLE_NAME_A = "value"
VARIABLE_NAME_B = "value"

Variable names must contain only uppercase or lowercase letters, digits and underscores, and can't begin with a digit.

USERNAME = "razvan"
db_host = "localhost"

Variable values are comprised by any arbitrary text, which can optionally be wrapped inside single (') or double (") quotes.

VERBOSE=true
DESTINATION_PATH="/tmp/data/out"

Notes:

  • Leading and trailing whitespace characters around variable keys and values are ignored unless they are enclosed within quotes.
  • Variables values are always parsed as text, which means that values such as 0 or true will be automatically converted to '0' and 'true'.
  • Commented lines that start with a hash-tag (#) are ignored.

Load an .env file using the CLI

To load the variables present in an .env file into the process environment through the CLI, you can use the --env-file flag:

$ node --env-file=/path/to/.env script.js

Example

Let's consider this .env file:

.env
DB_HOST=localhost
DB_PORT=3306

Let's consider this script that outputs the value of these environment variables:

showenv.js
console.log(`DB_HOST = ${process.env.DB_HOST}`);
console.log(`DB_PORT = ${process.env.DB_PORT}`);

Which when executed will produce this output:

$ node --env-file=.env showenv.js 
DB_HOST = localhost
DB_PORT = 3306

Load an .env file using the Node.js API

To load the variables present in an .env file into the process environment directly from your code, you can use the loadEnvFile() method of the process core module:

const { loadEnvFile } = require('node:process');

loadEnvFile(path?);

Where:

  • path is the optional path to the env file you want to load. Defaults to .env if undefined.

Example

Let's consider this .env file:

.env
DB_HOST=localhost
DB_PORT=3306

Let's consider this script that loads the .env file located in the same directory into the environment and outputs these variables in the form of an object literal:

loadenv.js
const { loadEnvFile } = require('node:process');

function loadenv() {
  // Load the contents of the .env file into the environment
  loadEnvFile();

  // Parse and return the contents of the `.env` file
  return {
    db: {
      host: process.env.DB_HOST,
      port: Number(process.env.DB_PORT)
    }
  };
}

// Retrieve and output the contents of the `.env` file
const env = loadenv();
console.log(env);

Which when executed will produce this output:

$ node loadenv.js
{ db: { host: 'localhost', port: 3306 } }

Enjoying the courses?

I've made these courses completely free so anyone can learn from them. If they've helped you and you'd like to actively support the work behind BackendBrewery, you can leave a tip:

Support BackendBrewery
Load Configuration Into the Environment in Node.js | Backend Brewery