TExcelTAD
Home › Node.js › Environment Variables & Config

Environment Variables & Config

The same program usually runs in several places: your laptop, a test server, production. Each place needs different settings — a port number, a database URL, an API key, a log level. The twelve-factor convention is to keep these settings out of the code and read them from environment variables.

Reading process.env

Every environment variable is available as a string property of process.env. Missing variables are undefined.

node · try it yourself
const { spawnSync } = require('node:child_process');

// Start a child Node process with a controlled environment so the output is predictable.
const script = `
  console.log('APP_NAME =', process.env.APP_NAME);
  console.log('PORT     =', process.env.PORT, typeof process.env.PORT);
  console.log('MISSING  =', process.env.MISSING);
`;

const result = spawnSync(process.execPath, ['-e', script], {
  env: { APP_NAME: 'shop', PORT: '8080' },
  encoding: 'utf8',
});
process.stdout.write(result.stdout);
APP_NAME = shop
PORT     = 8080 string
MISSING  = undefined

Note: Values are always strings. PORT=8080 gives you '8080', and DEBUG=false gives you the truthy string 'false'. Convert them explicitly.

On the command line you set variables for one run like this (Linux/macOS shells):

bash · try it yourself
$ PORT=8080 APP_NAME=shop node server.js
shop listening on port 8080
shop listening on port 8080

On Windows PowerShell it is $env:PORT=8080; node server.js.

A typed config module

Don't sprinkle process.env.X through your whole code base. Read everything once, convert and validate it, and export a frozen object. If something required is missing, fail at startup with a clear message — not hours later deep inside a request.

node · try it yourself
function loadConfig(env) {
  const errors = [];

  const required = (name) => {
    if (!env[name]) errors.push(`${name} is required`);
    return env[name];
  };
  const int = (name, fallback) => {
    if (env[name] === undefined) return fallback;
    const n = Number.parseInt(env[name], 10);
    if (Number.isNaN(n)) errors.push(`${name} must be a number`);
    return n;
  };
  const bool = (name, fallback) =>
    env[name] === undefined ? fallback : ['1', 'true', 'yes'].includes(env[name].toLowerCase());

  const config = {
    port: int('PORT', 3000),
    databaseUrl: required('DATABASE_URL'),
    debug: bool('DEBUG', false),
    logLevel: env.LOG_LEVEL ?? 'info',
  };

  if (errors.length) throw new Error('Invalid config: ' + errors.join(', '));
  return Object.freeze(config);
}

console.log(loadConfig({ DATABASE_URL: 'postgres://db/shop', DEBUG: 'TRUE' }));

try {
  loadConfig({ PORT: 'eighty' });
} catch (err) {
  console.log(err.message);
}
{
  port: 3000,
  databaseUrl: 'postgres://db/shop',
  debug: true,
  logLevel: 'info'
}
Invalid config: PORT must be a number, DATABASE_URL is required

In a real app you'd call loadConfig(process.env) in a config.js module and import the result everywhere.

.env files — built into Node

During development it is handy to keep variables in a .env file. The popular dotenv package used to be the only way to load it, but modern Node (20.6+) can do it itself:

bash
# .env  (never commit this file — add it to .gitignore)
PORT=4000
DATABASE_URL=postgres://localhost/shop_dev
API_KEY="dev-key-123"
How Since
node --env-file=.env app.js Node 20.6
node --env-file-if-exists=.env app.js (no error if missing) Node 22.9
process.loadEnvFile('.env') inside your code Node 21.7 / 20.12
util.parseEnv(text) — parse without touching process.env Node 21.7 / 20.12

Here is process.loadEnvFile() in action. The example writes a .env file first, loads it, and deletes it again:

node · try it yourself
const fs = require('node:fs');

fs.writeFileSync('.env', [
  '# local development settings',
  'GREETING=Hello from .env',
  'RETRIES=3',
  'QUOTED="spaces are kept"',
].join('\n'));

process.loadEnvFile('.env');

console.log(process.env.GREETING);
console.log(Number(process.env.RETRIES) + 1);
console.log(process.env.QUOTED);

fs.unlinkSync('.env');
Hello from .env
4
spaces are kept

Tip: Variables that already exist in the real environment win over values from the .env file. That lets a server override development defaults without editing files.

NODE_ENV

Many libraries look at NODE_ENV. Express, for example, caches templates and hides stack traces when NODE_ENV=production. Use it for that kind of behaviour switch, but keep actual settings (URLs, keys) in their own variables — "staging" and "production" are both production mode but talk to different databases.

Secrets

  • Keep secrets (passwords, tokens) only in environment variables or a secret manager, never in Git.
  • Commit a .env.example with fake values so teammates know which variables exist.
  • Don't log the whole config object in production — it may contain keys.

Test yourself

What is the type of process.env.PORT when you start a program with PORT=8080?

  1. number
  2. string
  3. bigint
  4. It depends on the value

How can modern Node load a .env file without any package?

  1. node --dotenv app.js
  2. node --env-file=.env app.js
  3. require('.env')
  4. It loads .env automatically

Why validate configuration at startup?

  1. It makes the program faster
  2. So missing or wrong settings fail immediately with a clear error
  3. Node requires it
  4. To encrypt the values