← Back to Node.js, page 4

nodejs-0072 · Medium mid

What do the twelve-factor rules mean for a Node.js service, and how do you load configuration that fails fast?

The twelve-factor method describes apps that are easy to deploy and scale: config in the environment, stateless processes, logs as a stream to stdout, fast start and graceful stop, backing services as attached resources, and the same code in every environment. A config module should read the environment once, validate every value, and stop the process with a clear message when something is wrong.

Full answer

Factors that matter most for Node services:

  • Codebase: one repository per app, many deploys from it.
  • Dependencies: declare everything in package.json and the lock file. Do not rely on global installs.
  • Config: store in environment variables, strictly separate from code. If the repository were public tomorrow, no secret should leak.
  • Backing services: databases, queues and caches are attached through URLs in config. Replacing a local database with a managed one needs no code change.
  • Build, release, run: build once (npm ci, compile), combine with config into a release, run it. Do not change code on a server.
  • Processes: stateless. Keep sessions and uploads in a database or object storage. This lets you run N copies.
  • Port binding: the app listens on a port from PORT. It does not rely on an external web server.
  • Concurrency: scale by adding processes, not by making one huge process.
  • Disposability: fast start-up, graceful shutdown on SIGTERM, jobs that survive a crash.
  • Dev and prod parity: same services and similar versions in development and production (containers help).
  • Logs: write to stdout as a stream of events. The platform collects them.
  • Admin processes: one-off tasks (migrations) run as separate commands in the same release.

Config loading rules:

  1. Read process.env in one module only.
  2. Convert types (numbers, booleans, lists) and apply defaults for non-secret values.
  3. Validate all values and report all problems in one message, not just the first one.
  4. Exit with a non-zero code at start-up when config is invalid. A service that boots with a bad config and fails later is much harder to diagnose.
  5. Freeze the result and never log secret values.
javascript
function loadConfig(env) {
  const errors = [];

  const text = (name, { required = true, secret = false, fallback } = {}) => {
    const value = env[name] ?? fallback;
    if (value === undefined || value === '') {
      if (required) errors.push(`${name} is required`);
      return undefined;
    }
    return value;
  };
  const integer = (name, { min = 0, max = 65535, fallback } = {}) => {
    const raw = env[name] ?? fallback;
    const value = Number(raw);
    if (raw === undefined || !Number.isInteger(value) || value < min || value > max) {
      errors.push(`${name} must be an integer from ${min} to ${max}, got ${JSON.stringify(raw)}`);
      return undefined;
    }
    return value;
  };
  const flag = (name, fallback = 'false') => {
    const raw = (env[name] ?? fallback).toLowerCase();
    if (!['true', 'false', '1', '0'].includes(raw)) {
      errors.push(`${name} must be true or false, got ${JSON.stringify(env[name])}`);
      return undefined;
    }
    return raw === 'true' || raw === '1';
  };

  const config = {
    port: integer('PORT', { fallback: '3000' }),
    databaseUrl: text('DATABASE_URL'),
    jwtSecret: text('JWT_SECRET', { secret: true }),
    debug: flag('DEBUG'),
    logLevel: text('LOG_LEVEL', { required: false, fallback: 'info' }),
  };

  if (errors.length > 0) {
    const error = new Error('Invalid configuration:\n  - ' + errors.join('\n  - '));
    error.code = 'INVALID_CONFIG';
    throw error;
  }
  return Object.freeze(config);
}

function describe(config) {
  // Never print secrets.
  return { ...config, jwtSecret: config.jwtSecret ? '[hidden]' : undefined };
}

// A good environment
const good = loadConfig({ PORT: '8080', DATABASE_URL: 'postgres://db/schoolabe', JWT_SECRET: 'long-random-value', DEBUG: 'false' });
console.log('valid config:', describe(good));
console.log('config is frozen:', Object.isFrozen(good));

// A bad environment: all problems are reported together.
try {
  loadConfig({ PORT: 'eighty', DEBUG: 'maybe' });
} catch (err) {
  console.log(err.code);
  console.log(err.message);
  // In a real service: console.error(err.message); process.exit(1);
}

The second call fails on purpose (error on purpose). A real service would print the message and exit with code 1 before it starts listening. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): valid config: { port: 8080, databaseUrl: 'postgres://db/schoolabe', jwtSecret: '[hidden]', debug: false, logLevel: 'info' } config is frozen: true INVALID_CONFIG Invalid configuration: - PORT must be an integer from 0 to 65535, got "eighty" - DATABASE_URL is required - JWT_SECRET is required - DEBUG must be true or false, got "maybe"

Key points

  • Config in the environment, processes stateless, logs to stdout.
  • One module reads and validates process.env.
  • Report all config errors together and exit at start-up.
  • Disposability means fast start and graceful stop.

Common mistakes

  • Reading process.env in many files.
  • Treating the string 'false' as false.
  • Starting the server with a missing setting and failing on the first request.
  • Logging the whole config object, including secrets.

Follow-ups

  • Which twelve-factor rule is hardest to follow with WebSockets?
  • How do feature flags relate to config?
  • How would you run database migrations as an admin process?

Tips

  • Pick four or five factors and give a Node example for each.
  • Say 'fail fast at start-up' and show validation.
  • Mention that secrets never reach the logs.