Thuta Learning
Node.js
AdvancedWeb DevelopmentBeginner

Environment Variables & Configuration

Node.jsLesson 1630 min

What you'll walk away with

  • Explain why every process.env value is a string or undefined
  • Parse ports, booleans and enum values strictly and stop at startup with a clear error
  • Load .env files with --env-file and process.loadEnvFile() and know which value wins
  • Keep config in one function that takes an env object, so it can be tested without global state

Explain it simply

Environment variables in plain language

Environment variables are key-value settings handed to a process from the outside. The same code can listen on port 3000 and talk to a local database on your laptop, then listen on 8080 and talk to a cloud database in production: only the environment changes, not the code. Node.js exposes them through the process.env object.

The key fact is that every value in process.env is a string, and a missing key is undefined. Even if you write PORT=3000, what reaches your code is the text "3000", not the number 3000. Numbers and booleans have to be converted and checked by you.

Problem → Why → Solution

The problem: trusting process.env directly

Imagine a deploy where someone forgot to set PORT. Number(undefined) is NaN, PORT="hello" is NaN too, and an empty PORT is worse: Number("") is 0, so the server quietly listens on a random port. The same code reads process.env in ten different files, so a missing DATABASE_URL is only discovered when the first user request hits it.

server-naive.mjs
import { createServer } from 'node:http';

const port = Number(process.env.PORT); // NaN, 0 or a real port: who knows?
const debug = Boolean(process.env.DEBUG); // "false" is truthy, so this is true

createServer(handler).listen(port);
// ...and deep inside a route, much later:
// const db = connect(process.env.DATABASE_URL); // undefined only fails here

Why this is dangerous

The configuration mistake happens in one place, but the failure shows up far away and much later. The process looks healthy, accepts traffic and then fails, or it never errors at all and simply runs on the wrong port with debug mode on. Checking config in one place at startup stops the deploy immediately with a clear message such as 'PORT must be an integer'.

Core concept: read, parse, validate, freeze

Treat environment data as untrusted input, just like user input. Read it once at startup, parse each value into the type you need, check every rule, and hand the rest of the app one config object made immutable with Object.freeze. If the config is wrong, throw before accepting a single request and let the process stop; that is called failing fast.

Parse strictly. Number() can return NaN or 0, so check Number.isInteger and the range. Boolean("false") is true, so compare boolean text against exactly "true" and "false" and reject anything else. ?? only applies the default for null or undefined, not for an empty string, so empty values need their own check.

Decide for each setting whether it is required or has a default. A default is fine only when every environment can live with it, such as LOG_LEVEL=info, or PORT=3000 for local work. A secret or an address that differs per environment, such as DATABASE_URL, should have no default at all: a wrong default is worse than a crash, because the app would quietly connect to the wrong database. Collecting every rule in one function lets a reviewer see the application's whole configuration contract on a single screen.

Know where values come from. In production the hosting platform or a secret manager sets the environment. Locally a .env file is convenient, and Node 22 reads it without any package: node --env-file=.env app.js, or process.loadEnvFile() from code. A variable already set by the shell or platform wins over the file, and with several --env-file flags, later files override earlier ones.

Raw textNaive conversionResult
undefined (missing)Number(raw)NaN
"" (empty)Number(raw)0, a random port
"false"Boolean(raw)true
"" (empty)raw ?? "info""", no default
One configuration boundary
  1. Platform or .env supplies strings
  2. buildConfig(env) parses + checks
  3. Bad value: throw at startup
  4. Good values: one frozen object

Outside the boundary everything is string | undefined; inside it, values are already typed and checked.

General pattern

javascript
function parseSetting(raw = 'default') {
  const value = convert(raw);
  if (!isValid(value)) throw new Error(`NAME is invalid: "${raw}"`);
  return value;
}

export function buildConfig(env = process.env) {
  return Object.freeze({ setting: parseSetting(env.NAME) });
}

export const config = buildConfig(); // runs once, at startup

Each setting gets its own parse function, and buildConfig takes the env object as a parameter, so production passes process.env while tests pass a plain object.

Worked example: port, log level and a feature flag

This example turns the text of a .env file into an object with parseEnv from node:util, without touching process.env. buildConfig then parses the port as a number, checks LOG_LEVEL against an allowlist, and turns FEATURE_EMAIL into a strict boolean. At the end, watch which error messages three broken environments produce.

config.mjs
import { parseEnv } from 'node:util';

const LOG_LEVELS = new Set(['debug', 'info', 'warn', 'error']);

function parsePort(raw = '3000') {
  const port = Number(raw);
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
    throw new Error(`PORT must be an integer from 1 to 65535, got "${raw}"`);
  }
  return port;
}

function parseBoolean(name, raw, fallback) {
  if (raw === undefined) return fallback;
  if (raw === 'true') return true;
  if (raw === 'false') return false;
  throw new Error(`${name} must be "true" or "false", got "${raw}"`);
}

function buildConfig(env) {
  const logLevel = env.LOG_LEVEL ?? 'info';
  if (!LOG_LEVELS.has(logLevel)) throw new Error(`Unknown LOG_LEVEL "${logLevel}"`);
  const databaseUrl = env.DATABASE_URL?.trim();
  if (!databaseUrl) throw new Error('Missing DATABASE_URL');

  return Object.freeze({
    port: parsePort(env.PORT),
    logLevel,
    databaseUrl,
    emailEnabled: parseBoolean('FEATURE_EMAIL', env.FEATURE_EMAIL, false),
  });
}

// The same text a .env file would contain; parseEnv does not touch process.env.
const fromFile = parseEnv('PORT=8080\nLOG_LEVEL=debug\nDATABASE_URL=postgres://db/app\n');
const config = buildConfig(fromFile);
console.log(config.port, typeof config.port, config.logLevel, config.emailEnabled);

try {
  config.port = 1; // ES modules run in strict mode, so this throws
} catch (error) {
  console.log(`${error.name}: port is still ${config.port}`);
}

const broken = [
  { DATABASE_URL: 'postgres://db/app', PORT: 'eighty' },
  { DATABASE_URL: 'postgres://db/app', FEATURE_EMAIL: 'yes' },
  { PORT: '3000' },
];
for (const env of broken) {
  try {
    buildConfig(env);
  } catch (error) {
    console.log(`config error: ${error.message}`);
  }
}

Code breakdown

  1. Strict port parsingif (!Number.isInteger(port) || port < 1 || port > 65535) {

    This one line rejects NaN, 0, 3.5 and anything out of range. The error message includes the raw value, so the mistake is obvious immediately.

  2. Boolean by exact textif (raw === 'true') return true;

    Only "true" and "false" are accepted; a value like "yes" raises an error instead of silently becoming true.

  3. Required valueif (!databaseUrl) throw new Error('Missing DATABASE_URL');

    ?.trim() turns both undefined and whitespace-only values into something empty, so a missing or blank value stops here.

  4. Parse without side effectsconst fromFile = parseEnv('PORT=8080\nLOG_LEVEL=debug\nDATABASE_URL=postgres://db/app\n');

    parseEnv returns the .env content as a plain object and does not modify process.env, which makes it convenient for tests.

  5. Frozen resultconfig.port = 1; // ES modules run in strict mode, so this throws

    Because of Object.freeze, the assignment is a TypeError in strict-mode ES modules; in a sloppy-mode script it would be silently ignored. freeze is shallow, so nested objects need their own freeze.

You should see
8080 number debug false
TypeError: port is still 8080
config error: PORT must be an integer from 1 to 65535, got "eighty"
config error: FEATURE_EMAIL must be "true" or "false", got "yes"
config error: Missing DATABASE_URL

Node.js's built-in .env support

For local development, write a .env file and load it with a command-line flag. Each line is KEY=value, and lines starting with # are comments.

.env
# local development only: never commit real secrets
PORT=3000
LOG_LEVEL=debug
DATABASE_URL=postgres://localhost:5432/app_dev
bash
node --env-file=.env src/server.js
# base values first, local overrides second (later files win)
node --env-file=.env --env-file=.env.local src/server.js
# optional file: newer Node 22 releases accept --env-file-if-exists
node --env-file-if-exists=.env src/server.js

To load from code, use process.loadEnvFile(path); without a path it reads ./.env. The snippet below shows the precedence rule: the platform already set APP_PORT, so the file does not overwrite it, while APP_LOG_LEVEL, present only in the file, is added. --env-file-if-exists arrived in a later Node 22 release, so check node --help on your version.

load-env.mjs
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

const dir = await mkdtemp(join(tmpdir(), 'env-demo-'));
const envFile = join(dir, '.env');
await writeFile(envFile, 'APP_PORT=3000\nAPP_LOG_LEVEL=debug\n');

process.env.APP_PORT = '8080'; // pretend the platform already set this
process.loadEnvFile(envFile); // fills in only the keys that are still missing

console.log(process.env.APP_PORT); // 8080: the real environment wins
console.log(process.env.APP_LOG_LEVEL); // debug: came from the file
await rm(dir, { recursive: true, force: true });

In real projects

In a real project: validate before the server starts

In real apps, src/config.js exports buildConfig and is the first import of the entry point. If the config is wrong, the process exits with a non-zero code before server.listen runs, so Kubernetes or your container platform sees the new deploy as unhealthy and keeps sending traffic to the old version.

  • Commit a .env.example with key names and safe placeholders only, and keep the real .env in .gitignore.
  • Inject production secrets (database passwords, API keys) through the hosting platform's secret settings or a secret manager.
  • In the startup log, pick non-secret fields such as port, mode and log level; never log the whole config object.
  • In larger TypeScript projects a schema library such as zod declares parsing, defaults and error messages for many fields, but the rule stays the same.

Common mistakes

Common configuration mistakes

Trusting Boolean("false")

Every non-empty string is truthy, so DEBUG=false turns debug mode on. !!process.env.X has the same flaw, and process.env.X === 'true' silently turns "TRUE" or a typo like "ture" into false. Accept exactly two texts and raise an error for anything else.

Reading process.env all over the codebase

Reading process.env.X directly inside route handlers and services skips validation, lets each place invent its own default, and forces tests to mutate and restore the global process.env. Centralise it in one config module and let the rest of the code import only the config object.

Committing or logging secrets

A password that reaches git history stays there even after you delete the file, so it must be rotated. console.log(config) likewise ships the password inside the database URL to your log system.

Best practices

Best practices

  • Write buildConfig(env = process.env) and pass plain objects in tests.
  • Give defaults only to settings where a default is genuinely safe; make production secrets required.
  • Put the variable name and the bad value in error messages (only the name for secrets).
  • Do not try to change config at runtime by mutating process.env.

Mini challenge

Mini challenge: mode-aware database config

Write databaseConfig(env). Normalise NODE_ENV and accept only development, test and production. In production a missing DATABASE_URL must fail immediately, and in test mode the production database must never be used, even when DATABASE_URL happens to be set.

  • Trim and lowercase NODE_ENV and reject unknown values
  • Require DATABASE_URL in production
  • Test mode uses only TEST_DATABASE_URL or a local test default
  • Return a frozen { mode, databaseUrl } and try it with five cases
database-config.mjs
function required(env, name) {
  // TODO: return the trimmed value or throw "Missing <name>"
}

function databaseConfig(env) {
  // TODO: normalise env.NODE_ENV (default 'development')
  // TODO: reject anything that is not development, test or production
  // TODO: choose databaseUrl per mode (test must never read DATABASE_URL)
  // TODO: return a frozen { mode, databaseUrl }
}

const cases = [
  { NODE_ENV: 'test', DATABASE_URL: 'postgres://prod-db/app' },
  { NODE_ENV: 'Production', DATABASE_URL: 'postgres://prod-db/app' },
  {},
  { NODE_ENV: 'production' },
  { NODE_ENV: 'staging' },
];
// TODO: print each result, or "startup refused: <message>"

Expected: test uses the local test URL, 'Production' is normalised to production, and the empty object gets the development default. Production without DATABASE_URL and staging are both refused at startup.

Show hint

Write an explicit if/else if per mode. If the test branch never reads env.DATABASE_URL at all, you are safe even when a production URL leaks into the CI environment.

Show solution
database-config.mjs
function required(env, name) {
  const value = env[name]?.trim();
  if (!value) throw new Error(`Missing ${name}`);
  return value;
}

function databaseConfig(env) {
  const mode = (env.NODE_ENV ?? 'development').trim().toLowerCase();
  if (!['development', 'test', 'production'].includes(mode)) {
    throw new Error(`Unknown NODE_ENV "${mode}"`);
  }

  let databaseUrl;
  if (mode === 'test') {
    databaseUrl = env.TEST_DATABASE_URL ?? 'postgres://localhost/app_test';
  } else if (mode === 'production') {
    databaseUrl = required(env, 'DATABASE_URL');
  } else {
    databaseUrl = env.DATABASE_URL ?? 'postgres://localhost/app_dev';
  }
  return Object.freeze({ mode, databaseUrl });
}

const cases = [
  { NODE_ENV: 'test', DATABASE_URL: 'postgres://prod-db/app' },
  { NODE_ENV: 'Production', DATABASE_URL: 'postgres://prod-db/app' },
  {},
  { NODE_ENV: 'production' },
  { NODE_ENV: 'staging' },
];
for (const env of cases) {
  try {
    const config = databaseConfig(env);
    console.log(config.mode, config.databaseUrl, Object.isFrozen(config));
  } catch (error) {
    console.log(`startup refused: ${error.message}`);
  }
}

Quick quiz 1 / 3

If PORT is not set, what does Number(process.env.PORT) return?

Quick quiz 2 / 3

The shell has PORT=8080 and .env contains PORT=3000. Running node --env-file=.env app.js, what is process.env.PORT?

Quick quiz 3 / 3

Which code is the best way to parse FEATURE_EMAIL?

What to remember

  • Every process.env value is a string or undefined; parse numbers and booleans strictly yourself.
  • Read, validate and freeze config once at startup, and stop before accepting requests if it is wrong.
  • In Node 22, --env-file and process.loadEnvFile() load .env files without packages, and the existing environment wins.
  • buildConfig(env) takes a plain object, so it can be tested without touching global state.
  • Never commit or log secrets; keep only placeholders in .env.example.

Node.js Documentation — Environment Variables — Node.js

Node.js Documentation — --env-file — Node.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Environment Variables & Configuration | Thuta Learning