Environment Config: One Codebase, Many Worlds

Environment Config: One Codebase, Many Worlds in JavaScript: Your app has to run in at least three places: your laptop, a staging server, and production.

Concept Explanation

Your app has to run in at least three places: your laptop, a staging server, and production. They differ in database URL, API keys, log verbosity, feature flags, and which payment provider is the real one.

The naive answer is an if (isProduction) sprinkled through the code, or a config.prod.js you swap at build time. Both rot within a month.

The professional answer comes from the twelve-factor app rules: one artifact, injected configuration. You build the code exactly once and deploy that identical bundle everywhere. What changes between environments is not the code, it is the environment variables handed to it. This is what makes "the same build that passed staging is the build in production" a true statement instead of a hope.

The corollary matters just as much: secrets never enter the repository. Not in a config file, not in a comment, not "temporarily". Git remembers forever, and a private repo becomes a public one the day someone gets phished.


Syntax or Core Structure

Local development

# .env.local  --  gitignored, never committed
DATABASE_URL=postgres://localhost:5432/app_dev
STRIPE_SECRET_KEY=sk_test_xxx
LOG_LEVEL=debug
# .env.example  --  committed, no real values, documents what is needed
DATABASE_URL=
STRIPE_SECRET_KEY=
LOG_LEVEL=info

Validate at startup, not at first use

// config.js
import { z } from 'zod';

const schema = z.object({
  NODE_ENV: z.enum(['development', 'test', 'production']),
  DATABASE_URL: z.string().url(),
  STRIPE_SECRET_KEY: z.string().min(1),
  PORT: z.coerce.number().default(3000),
  LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']).default('info')
});

const parsed = schema.safeParse(process.env);
if (!parsed.success) {
  console.error('Invalid environment:', parsed.error.flatten().fieldErrors);
  process.exit(1);          // fail loudly at boot
}

export const config = parsed.data;

Frontend variables are public. Always.

// Vite exposes ONLY variables prefixed with VITE_ to the browser bundle.
const apiUrl = import.meta.env.VITE_API_URL;   // fine, it is not a secret

// Next.js uses NEXT_PUBLIC_ for the same purpose.
// Anything reaching the browser is readable by anyone. There is no
// such thing as a secret in client-side JavaScript.

Key Features

  • .env files are a development convenience, not a deployment mechanism. In production the platform injects real environment variables.
  • Precedence usually runs: real environment variables, then .env.local, then .env.<mode>, then .env. Know your tool's order.
  • Build-time versus run-time. A frontend bundle bakes values in at build time, so changing one requires a rebuild. A Node server reads them at boot, so a restart is enough.
  • Secret managers (AWS Secrets Manager, Vault, Doppler) add rotation, audit logs and access control on top of plain variables.

Real World Example

The test key that took payments for a week. A team kept both Stripe keys in one committed config.js and selected between them with a hostname check. A staging domain was added, the check did not match it, and staging quietly began issuing live charges against real cards. Nobody noticed until reconciliation.

Two habits would each have prevented it independently: never commit keys at all, and validate at boot that the key prefix matches the environment (sk_test_ outside production, sk_live_ only in it). Config bugs are rarely subtle in hindsight and almost always expensive.


Common Mistakes

  • Committing .env. Add it to .gitignore before you create it. If it is already in history, rotate every key in it; deleting the file is not enough.
  • Putting a secret in a VITE_/NEXT_PUBLIC_ variable. You have published it. Anyone can read it in DevTools.
  • Reading process.env scattered across forty files. One typo becomes an undefined that surfaces as a confusing error hours into a deploy. Centralise and validate.
  • Failing lazily. Discovering a missing variable when the first user hits checkout is far worse than refusing to boot.
  • Forgetting everything is a string. process.env.DEBUG === 'false' is false, but Boolean(process.env.DEBUG) is true. Coerce explicitly.
  • No .env.example. The next developer spends an afternoon reverse-engineering which variables the app needs.

Best Practices

  • Build once, deploy the same artifact everywhere, and vary only the injected configuration.
  • Validate the whole environment against a schema at startup and exit non-zero on failure.
  • Export a single typed config object and import that; forbid process.env elsewhere with a lint rule.
  • Commit .env.example with keys and no values, and keep it current in the same PR that adds a variable.
  • Use the platform's secret store for production, scoped per environment, and rotate on a schedule and after any suspected exposure.
  • Assert environment invariants explicitly: production must not hold test keys, and development must not hold live ones.

Practice Exercises

  1. The Boot Guard: Add schema validation for three environment variables to a small project and confirm the app refuses to start when one is missing or malformed.
  2. The Public Variable: Put a value in a VITE_-prefixed variable, build the app, and find that value inside the generated bundle. Write one sentence explaining what that means for API keys.
  3. The Example File: Write a .env.example plus a short README section for a project of yours, so a new developer can get running without asking anyone.