Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to read an environment variable in Node.js

Short answer

All environment variables are in the process.env object. A missing variable is undefined, so add a default value:

const port = process.env.APP_PORT ?? '3000';
const mode = process.env.APP_MODE ?? 'development';
 
console.log(port, mode);

Output:

3000 development

Numbers and flags

Values are always strings. Convert them yourself:

process.env.MAX_USERS = '50';
process.env.DEBUG = 'false';
 
const maxUsers = Number(process.env.MAX_USERS);
const debug = process.env.DEBUG === 'true';
 
console.log(maxUsers + 1, debug);

Output:

51 false

Setting a variable for one run

In the terminal, a variable is set before the command. On Windows PowerShell the syntax is different:

APP_PORT=8080 node server.js
 
# Windows PowerShell
$env:APP_PORT=8080; node server.js

A .env file

Node.js can load variables from a .env file itself with the --env-file flag:

# .env
DATABASE_URL=postgres://localhost/shop
API_KEY=test-key
 
node --env-file=.env app.js

Common mistake

A required variable that is missing should stop the program right away with a clear message, not fail later somewhere deep in the code:

const required = (name) => {
  const value = process.env[name];
  if (!value) throw new Error(`Environment variable ${name} is not set`);
  return value;
};
 
try {
  required('SOME_MISSING_VARIABLE');
} catch (error) {
  console.log(error.message);
}

Output:

Environment variable SOME_MISSING_VARIABLE is not set

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.