Zod Nested Environment Config
Flatten process.env into a strongly typed nested config with Zod, supporting defaults, optional sections, and fail-fast startup checks.
Code
import { z } from 'zod';
const ConfigSchema = z.object({
NODE_ENV: z.enum(['development', 'staging', 'production']),
PORT: z.coerce.number().int().min(1).max(65535).default(3000),
DATABASE_URL: z.string().url(),
DATABASE_POOL_MAX: z.coerce.number().int().min(1).max(100).default(10),
REDIS_URL: z.string().url().optional(),
FEATURES: z.string().transform((raw, ctx) => {
const flags = raw.split(',').map((f) => f.trim()).filter(Boolean);
const known = ['audit', 'beta-ui', 'webhooks'] as const;
for (const f of flags) {
if (!known.includes(f as never)) {
ctx.addIssue({ code: 'custom', message: 'unknown feature flag: ' + f });
return z.NEVER;
}
}
return flags;
}).default(''),
});
type AppConfig = z.infer<typeof ConfigSchema>;
function loadConfig(source: Record<string, string | undefined>): AppConfig {
const parsed = ConfigSchema.safeParse(source);
if (!parsed.success) {
const report = parsed.error.issues
.map((i) => i.path.join('.') + ': ' + i.message)
.join('; ');
throw new Error('invalid environment configuration -> ' + report);
}
return parsed.data;
}
export const config = loadConfig(process.env as Record<string, string | undefined>);
export const isProd = config.NODE_ENV === 'production';What the snippet does
Structurally, expect the function loadConfig and nothing else.
Repetition is confined to for (const f of flags) — the rest of the file is straight-line. Everything borrowed from zod is visible in one line: z. Error is the guard’s signal — thrown at the branch, before any partial work happens.
Caveats
- Plan for an install step:
zodis a real dependency, resolved by the package manager.
Applying it
Entry signature: export const config =
Import config from the file and call it — the rest of the code is implementation detail.
Statements that matter
const flags = raw.split(',').map((f) => f.trim()).filter(Boolean);
throw new Error('invalid environment configuration -> ' + report);
const known = ['audit', 'beta-ui', 'webhooks'] as const;
Interactive Tools for This Topic
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.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.
FAQ
- How are precondition violations signaled?
- Validation comes first — `Error` marks the failure, before any partial work happens.
- 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.