Node.js theorytheory 0/50 · 0%
Patterns · medium

24. Environment-based configuration

Twelve-factor config: same code, different environments.

Production Node apps read all configuration — ports, database URLs, RPC endpoints, feature flags — from the environment rather than hard-coded values, so the same built artifact runs unchanged across dev, staging and production.

js
function loadConfig() {
  const required = ["RPC_URL", "DATABASE_URL"];
  for (const key of required) {
    if (!process.env[key]) throw new Error(`missing required env var: ${key}`);
  }
  return {
    port: Number(process.env.PORT ?? 3000),
    rpcUrl: process.env.RPC_URL,
    databaseUrl: process.env.DATABASE_URL,
    isProd: process.env.NODE_ENV === "production",
  };
}

Fail fast at startup if required configuration is missing — discovering a missing `DATABASE_URL` mid-request, after already accepting traffic, is far worse than crashing immediately with a clear error at boot.

Check your understanding

  1. 1. Why read config from environment variables instead of hard-coding it?

  2. 2. When should missing required configuration be detected?

  3. 3. What does process.env.NODE_ENV commonly indicate?