Config Schema Validate From Env
Load and validate configuration from environment variables with Zod schema and defaults.
Code
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:
zodis 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.
FAQ
- Are there third-party dependencies?
- `zod` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.