Config Schema Validate From Env

Load and validate configuration from environment variables with Zod schema and defaults.

TypescriptConfig Management

Code

typescriptsnippet
1 line
import{z}from'zod';const configSchema=z.object({port:z.coerce.number().int().min(1).max(65535).default(3000),nodeEnv:z.enum(['development','staging','production']).default('development'),logLevel:z.enum(['debug','info','warn','error']).default('info'),databaseUrl:z.string().url(),redisUrl:z.string().url().optional()});export type Config=z.infer<typeof configSchema>;export function loadConfig(env:Record<string,string|undefined>=process.env):Config{return configSchema.parse({port:env.PORT,nodeEnv:env.NODE_ENV,logLevel:env.LOG_LEVEL,databaseUrl:env.DATABASE_URL,redisUrl:env.REDIS_URL});}

How it works

The working surface is the function loadConfig — everything else is wiring.

From zod it pulls z — the imports name exactly which library surface the snippet touches.

Caveats

  • Plan for an install step: zod is a real dependency, resolved by the package manager.

Putting it to use

The primary signature is export function loadConfig(env:Record<string,string|undefined>=process.env)

The surface worth importing is loadConfig; the helpers around it are private to the snippet.

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
`zod` — install it with the package manager before running.