Environment Variables Done Right: From .env Files to Production Configs
Hardcoded config values are the fastest way to ship broken code to the wrong environment. Here is how to manage configuration properly. The Config Module Pattern import { z } from "zod"; const envS...

Source: DEV Community
Hardcoded config values are the fastest way to ship broken code to the wrong environment. Here is how to manage configuration properly. The Config Module Pattern import { z } from "zod"; const envSchema = z.object({ NODE_ENV: z.enum(["development", "staging", "production"]).default("development"), PORT: z.coerce.number().default(3000), DATABASE_URL: z.string().url(), REDIS_URL: z.string().url(), JWT_SECRET: z.string().min(32), LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]).default("info"), }); const parsed = envSchema.safeParse(process.env); if (\!parsed.success) { console.error("Invalid environment variables:", parsed.error.flatten()); process.exit(1); } export const config = parsed.data; export type Config = z.infer<typeof envSchema>; Why Validation at Startup Without validation, a missing DATABASE_URL crashes your app at the first query, not at startup. By then your health check passed, load balancer routed traffic, and users see 500 errors. Validate early, fail fast. E