Challenge 2: Fail Fast on Boot — Possible Solution ==================================================================== import { z } from "zod"; const ConfigSchema = z.object({ NODE_ENV: z.enum(["development", "production", "test"]), PORT: z.coerce.number().int().positive(), LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]), }); type Config = z.infer; function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { const result = ConfigSchema.safeParse(env); if (!result.success) { console.error("❌ Invalid configuration. Fix these issues and restart:\n"); for (const issue of result.error.issues) { console.error(` - ${issue.path.join(".")}: ${issue.message}`); } process.exit(1); } return result.data; } // Called once, at the very top of the app's entry point — // before setting up routes, connecting to a database, or starting a server. export const config = loadConfig(); // If NODE_ENV or PORT is missing/invalid, the process exits immediately // with a clear message, e.g.: // // ❌ Invalid configuration. Fix these issues and restart: // // - PORT: Expected number, received nan // - NODE_ENV: Invalid enum value. Expected 'development' | 'production' | 'test', received undefined // // instead of crashing three requests into production with a vague // "Cannot read properties of undefined" deep inside some handler. WHY THIS WORKS -------------- - safeParse() (instead of parse()) returns a { success, data } or { success, error } result rather than throwing — that lets us print every validation issue at once instead of stopping at the first one. - process.exit(1) ensures a misconfigured app never starts serving traffic at all — "fail fast" means failing at boot, in full view of whoever deployed it, not failing later against a real user's request. - Accepting `env` as a parameter (defaulting to process.env) makes loadConfig() itself testable — a test can pass a fake env object without needing to mutate the real process.env.