Tutorial

Configuration Management Across Environments

Resolve configuration from many sources with explicit precedence, validate it at startup, and keep secrets out of code and logs with 12-factor discipline.

On this page

  1. Introduction
  2. The Twelve-Factor Principles
  3. Defining the Schema and Validating at Startup
  4. Precedence and Layered Sources
  5. Secrets: Handling and Hygiene
  6. Environment Parity and the .env.example Contract
  7. Config Validation in CI and the Feature Flag Lifecycle
  8. Conclusion

Introduction

Configuration is everything your application needs to run that is not code: database URLs, feature flags, log levels, third-party API keys, the port to listen on. It differs across environments — local, CI, staging, production — and it changes more often than the code does. The two classic failure modes are hardcoding (the config that cannot change without a redeploy and that leaks secrets into version control) and unvalidated environment variables (the process.env.DATABASE_URL that is undefined in production, discovered at the first database call at 3 a.m.). Both are solved by the same discipline: externalize all configuration, resolve it from explicit sources in a defined precedence, and validate the final shape at startup before the application accepts traffic.

This article builds a configuration system following the twelve-factor methodology: a single source of truth resolved from environment variables, validated by a schema, typed throughout the codebase, and with secrets handled so they never appear in logs, error messages, or version control.

The Twelve-Factor Principles

The twelve-factor app methodology states three rules for config. First, store config in the environment — not in constants files, not in YAML checked into git, but in environment variables that vary by deploy. Second, keep config strictly separate from code — code is the same across environments; config is what differs. Third, config should not be checked into the code repository — secrets in git are a vulnerability, and environment-specific values in git create merge conflicts and drift.

The practical consequence is that your application reads its entire configuration from process.env (or the equivalent) at startup. Files like .env are a development convenience, loaded into the environment by a tool like dotenv; in production, the platform injects the variables directly. The code never imports a config/prod.ts — there is no such file.

Defining the Schema and Validating at Startup

Reading process.env.DATABASE_URL directly is fragile: the variable may be missing, it may be the wrong type (every env var is a string), and the failure surfaces only when the code uses it. The fix is to define the expected configuration as a schema, parse and coerce the environment into that shape, and fail fast at startup if anything is missing or invalid. A startup failure is a deployment failure caught by your CI and rollback; a runtime undefined is a production incident.

import { z } from "zod";

const configSchema = z.object({
  nodeEnv: z.enum(["development", "test", "staging", "production"]).default("development"),
  port: z.coerce.number().int().positive().default(3000),
  logLevel: z.enum(["debug", "info", "warn", "error"]).default("info"),
  databaseUrl: z.string().url(),
  redisUrl: z.string().url().optional(),
  jwtIssuer: z.string().min(1),
  jwtPublicKey: z.string().min(1),
  featureFlags: z.object({
    newDashboard: z.coerce.boolean().default(false),
    betaExport: z.coerce.boolean().default(false),
  }),
  rateLimit: z.object({
    windowMs: z.coerce.number().int().positive().default(60_000),
    max: z.coerce.number().int().positive().default(100),
  }),
});

export type Config = z.infer<typeof configSchema>;

function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
  const parsed = configSchema.safeParse({
    nodeEnv: env.NODE_ENV,
    port: env.PORT,
    logLevel: env.LOG_LEVEL,
    databaseUrl: env.DATABASE_URL,
    redisUrl: env.REDIS_URL,
    jwtIssuer: env.JWT_ISSUER,
    jwtPublicKey: env.JWT_PUBLIC_KEY,
    featureFlags: {
      newDashboard: env.FF_NEW_DASHBOARD,
      betaExport: env.FF_BETA_EXPORT,
    },
    rateLimit: {
      windowMs: env.RATE_LIMIT_WINDOW_MS,
      max: env.RATE_LIMIT_MAX,
    },
  });
  if (!parsed.success) {
    const issues = parsed.error.issues.map(i => `${i.path.join(".")}: ${i.message}`).join("\n");
    throw new Error(`Invalid configuration:\n${issues}`);
  }
  return parsed.data;
}

export const config = loadConfig();

The z.coerce.number() and z.coerce.boolean() handle the string-to-type conversion, and the defaults make optional config explicit. The error message lists every invalid field, so a misconfigured deploy fails with a readable list rather than a single cryptic stack trace. Because config is a typed constant, every consumer gets autocomplete and compile-time guarantees — you cannot typo config.databaseUrl and discover it at runtime.

Precedence and Layered Sources

Real applications draw config from more than one source: a .env file for local development, environment variables injected by the platform, command-line flags for one-off overrides, and a remote config service for feature flags that change without a redeploy. The key is an explicit, documented precedence so it is always clear which source wins. A common order, highest to lowest, is: command-line flags, environment variables, a local .env file (development only), and built-in defaults. Never have two sources at the same precedence with no rule for which wins — that is the configuration equivalent of a race condition.

import { config as loadDotenv } from "dotenv";

if (process.env.NODE_ENV !== "production") {
  loadDotenv(); // populate process.env from .env, but never override existing vars
}
// CLI flags override env via a parser; env overrides .env; defaults are in the schema.

For feature flags that must change at runtime without a redeploy, layer a remote config service (LaunchDarkly, Unleash, or a self-hosted store) on top of the static startup config. The startup config is the immutable baseline; the remote service is the mutable overlay. Keep the remote service behind a fallback so a service outage degrades to the startup defaults rather than crashing the app.

Secrets: Handling and Hygiene

Secrets are configuration with a higher stakes: a leaked database URL or signing key is a security incident. The rules are strict. Never commit secrets to version control — use environment injection or a secrets manager (Vault, AWS Secrets Manager, Cloudflare secrets), and put .env in .gitignore. Never log a secret — structured loggers can be configured with a redaction layer that strips known sensitive keys, but the safer rule is to never put a secret into a loggable object in the first place. Never include a secret in an error message sent to the client; the error message that includes the database connection string is a classic leak.

// Wrap secrets so they are not accidentally serialized.
class Secret {
  constructor(private readonly value: string) {}
  get(): string { return this.value; }
  toJSON(): string { return "[redacted]"; } // safe for structured logs
  toString(): string { return "[redacted]"; }
}

const config = {
  ...loadConfig(),
  jwtPublicKey: new Secret(raw.jwtPublicKey),
  databaseUrl: new Secret(raw.databaseUrl),
};

Rotating secrets is part of the lifecycle. Design the system so a secret can be rotated without downtime: support multiple valid keys simultaneously (a key id in the JWT header selects which key verifies), and rotate by adding the new key, waiting for old tokens to expire, then removing the old key. A secret that requires a restart to change is a secret that never gets rotated.

Environment Parity and the .env.example Contract

Environments drift when their configuration diverges silently. Maintain a .env.example checked into version control that lists every variable the application expects, with a placeholder value and a comment describing its purpose. This file is the contract between the application and the people who deploy it: it is how a new developer sets up local config, and it is how an operator knows which variables to inject in production. When you add a config key, you add it to .env.example in the same commit; when CI starts, it reads .env.example and fails if a required variable is not set in the CI environment. This closes the drift gap — a variable missing in production is caught at deploy time, not at first use.

Keep environments as similar as possible. The production database should be the same engine as staging, not a different vendor. Feature flags should exist in all environments, not only production. The bug that appears only in production because production is the only environment with a particular config value is the hardest bug to reproduce; parity makes it reproducible in staging.

Config Validation in CI and the Feature Flag Lifecycle

Validating configuration at startup catches misconfiguration before it reaches production, but the ideal is to catch it before it reaches the startup — at deploy time, in CI. The same schema that parses process.env in the application can run as a CI step against the environment the deploy will use, so a missing variable fails the pipeline rather than the freshly-started pod. Wire the validation into the deployment workflow: a step that loads the environment (from the secrets manager, the platform’s environment export, or a dry-run of the deploy) and runs the schema parse, exiting non-zero on failure. This shifts the failure left from a runtime crash to a CI red light, which is cheaper to find and impossible to miss.

// scripts/validate-config.ts — a CI step that fails the build on bad config.
import { configSchema } from "../src/config";
const result = configSchema.safeParse(loadDeployEnvironment());
if (!result.success) {
  console.error("Configuration is invalid for this environment:");
  for (const issue of result.error.issues) console.error(`  ${issue.path.join(".")}: ${issue.message}`);
  process.exit(1);
}
console.log("Configuration valid.");

Keep a config.example or .env.example as the contract and assert in CI that every variable it lists is present in the target environment, and that no required variable is empty. This catches the two failure modes that a schema alone might miss: a variable that is present but empty (which a z.string().min(1) catches, but only if you wrote the constraint), and a variable that the application no longer reads but the deploy still sets (drift in the other direction). A periodic diff between the schema’s keys and the deployed environment’s keys surfaces both.

Feature flags are configuration that changes at runtime, and they deserve a lifecycle of their own. A flag is born to gate a risky rollout, lives for the duration of the rollout, and should die when the feature is permanent. The failure mode is flag debt: flags accumulate, every flag is a branch in the code that must be tested, and a codebase with a hundred permanent flags is a codebase nobody can reason about. Give every flag an owner, an expiry date, and a reason. Audit periodically for expired flags and remove them — the removal is a small PR that deletes the flag check and the dead branch, and it keeps the codebase honest.

// A flag with metadata that makes its lifecycle visible.
const FLAGS = {
  newCheckout: { enabled: true, owner: "team-payments", expires: "2025-04-01", reason: "gradual rollout of redesigned checkout" },
  betaExport:   { enabled: false, owner: "team-data",    expires: "2025-06-01", reason: "beta access for CSV export" },
} as const;

function isEnabled(flag: keyof typeof FLAGS, user: User): boolean {
  const meta = FLAGS[flag];
  if (new Date(meta.expires) < new Date()) {
    logger.warn({ flag, msg: "feature flag is expired and should be removed" });
  }
  return meta.enabled && evaluateTargeting(flag, user); // cohort, percentage, etc.
}

The warning on an expired flag is the signal that drives cleanup. Targeting — who sees the flag — is a separate concern from whether the flag is on; a flag may be on for 10% of users, on for a specific cohort, or on for everyone. Express the targeting explicitly (a percentage, a cohort id, an attribute match) rather than as ad-hoc conditions, so the rollout is reproducible and the flag can be turned off by changing one number. For a percentage rollout, use a consistent hash of the user id so the same user always sees the same result — a user who sees the new checkout on one request and the old one on the next is a user who notices the bug you are trying to catch.

The remote config service that backs runtime flags should be a layer on top of the startup config, not a replacement for it. The startup config is the immutable baseline (the database URL, the signing key); the flag service is the mutable overlay (which features are on). If the flag service is down, the application falls back to the startup defaults, so a flag-service outage does not take down features — it freezes them in their last-known state, which is a safe degradation. Cache the flag values locally with a short TTL, so a flag toggle takes effect within seconds without a dependency on the flag service for every request.

Conclusion

Configuration management is a discipline of externalization, precedence, validation, and secret hygiene. Externalize every environment-varying value into the environment; resolve it from explicit sources in a documented order; validate the final shape against a schema at startup so misconfiguration fails the deploy rather than the runtime; type the result so the codebase carries the guarantee; and treat secrets as a distinct class that is never committed, never logged, and rotatable without downtime. The payoff is an application that starts the same way in every environment, fails loudly when misconfigured, and keeps its secrets secret.

Related Examples