Testing, Performance & Deployment
Node.js Environment and Configuration Management
Configuration should be read once at startup, validated, and exported as a frozen object. Reading process.env throughout the codebase scatters defaults and hides missing values until runtime.
What is Environment and Configuration Management in Node.js?
Configuration should be read once at startup, validated, and exported as a frozen object. Reading process.env throughout the codebase scatters defaults and hides missing values until runtime.
Environment and Configuration Management example
JavaScript
import { z } from 'zod';
const schema = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
PORT: z.coerce.number().default(3000),
MONGODB_URI: z.string().url(),
JWT_SECRET: z.string().min(32),
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);
}
export const config = Object.freeze(parsed.data);Key points to remember
- Fail at startup on invalid configuration, not on the first request that needs it.
- Coerce types once — every environment variable arrives as a string.
- Never read process.env outside this module.
- Keep a committed .env.example listing every required name.
Node.js Environment and Configuration Management— Interview Questions & FAQs
Why validate environment variables at startup?+
Because a missing JWT_SECRET should crash the deploy immediately, not fail silently until the first login attempt at 2 a.m. Validation turns a runtime mystery into a startup error.
