Ch. 6 · Node.js

Node.js Environment Variables and Configuration

Node.js Environment Variables and Configuration. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readintermediateupdated Oct 3, 2026

Environment variables are external strings and need parsing and validation. Defaults should distinguish missing configuration from explicitly supplied values.

Before you start

You should know JavaScript promises, asynchronous errors and the distinction between a process and a request. When following a server example, identify the resource owner and the point where work completes. Try experiments locally with bounded input instead of assuming production traffic behaves like a single request.

The practical goal is to reason through this situation: Parse a PORT value and reject values outside the supported range. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Treat configuration as text

PORT and feature flags arrive as strings or undefined. Do not rely on truthiness to infer their meaning.

Step 2: Parse explicit accepted forms

Check numeric syntax and range; recognize documented true and false spellings and reject unknown flag values.

Step 3: Fail startup predictably

Report invalid configuration before serving requests, with sensitive values excluded from diagnostics.

Worked scenario

Parse a PORT value and reject values outside the supported range.

function flag(value) {
  if (value === undefined || value === 'false') return false;
  if (value === 'true') return true;
  throw new Error('Invalid feature flag');
}
console.log(flag('false')); // false
JavaScript

Boolean(‘false’) would produce true. For a port, also reject empty or malformed input before checking its integer range.

Common mistake

Boolean(‘false’) is true because the string is nonempty.

Verify the behavior

Test missing, valid and invalid forms, including empty strings. Verify errors identify the setting without printing secrets.

Interview exercise

Validate a feature flag.

Answer and reasoning

Accept documented spellings explicitly, reject unknown values and keep sensitive configuration out of logs.

Continue learning

Compare the scenario with the Node.js interview questions and test your understanding with the Node.js MCQs. For terminology and implementation details, consult the reference material.

More in Node.js

read ✓Node.js · hard

Node.js Clustering Across CPU Cores

Use cluster to run several workers on all cores, restart crashed workers, and understand shared-port and shared-state limits.

~2 min readread →
read ✓Node.js · hard

Node.js Password Hashing with scrypt

Store passwords as salted hashes with a slow key-derivation function, and compare candidates in constant time.

~2 min readread →
esc