
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 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 the
Continue reading on Dev.to Tutorial
Opens in a new tab



