Node.js › Environment Variables & Configuration
How would you validate that all required environment variables are present and correctly typed at application startup, rather than discovering a missing one at runtime?
IntermediateAnswer
Validating configuration eagerly at startup (using a schema validation library like zod, joi, or envalid) causes the application to fail fast with a clear error message immediately on boot if a required environment variable is missing or malformed, rather than the more dangerous alternative of the application starting successfully but failing unpredictably later, deep inside some unrelated code path, when that specific configuration value is finally accessed.
const { z } = require('zod');
const envSchema = z.object({
DATABASE_URL: z.string().url(),
PORT: z.coerce.number().default(3000),
NODE_ENV: z.enum(['development', 'production', 'test']),
});
const env = envSchema.parse(process.env); // throws immediately with a clear error if invalidReal-world example A production deployment that was accidentally missing its DATABASE_URL environment variable used to fail confusingly deep inside a database query several minutes after startup; adding zod-based startup validation now makes the process crash immediately with a clear 'DATABASE_URL is required' error the moment it boots, making the root cause obvious right away.