typescript 47 lines · 8 steps

Validating config with Zod schemas

A Zod schema validates untrusted config at runtime and produces a fully typed, guaranteed-valid object.

Explained by highlit
1import { z } from "zod";
2 
3const DatabaseSchema = z.object({
4 host: z.string().min(1),
5 port: z.number().int().min(1).max(65535),
6 ssl: z.boolean().default(false),
7 pool: z.object({
8 min: z.number().int().nonnegative(),
9 max: z.number().int().positive(),
10 }).refine((p) => p.max >= p.min, {
11 message: "max must be >= min",
12 path: ["max"],
13 }),
14});
15 
16const ConfigSchema = z.object({
17 env: z.enum(["development", "staging", "production"]),
18 database: DatabaseSchema,
19 features: z.record(z.string(), z.boolean()).default({}),
20 workers: z.array(z.object({
21 name: z.string(),
22 concurrency: z.number().int().positive(),
23 })).min(1),
24});
25 
26export type Config = z.infer<typeof ConfigSchema>;
27 
28export interface ConfigIssue {
29 path: string;
30 message: string;
31}
32 
33export function loadConfig(raw: unknown): Config {
34 const result = ConfigSchema.safeParse(raw);
35 if (result.success) return result.data;
36 
37 const issues: ConfigIssue[] = result.error.issues.map((issue) => ({
38 path: issue.path.length ? issue.path.join(".") : "<root>",
39 message: issue.message,
40 }));
41 
42 const report = issues
43 .map((i) => ` \u2022 ${i.path}: ${i.message}`)
44 .join("\n");
45 
46 throw new Error(`Invalid configuration:\n${report}`);
47}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Zod schemas double as both runtime validators and the single source of truth for static types.
  2. 2refine lets you attach cross-field invariants that simple field types can't express.
  3. 3safeParse plus issue mapping turns raw validation failures into readable, actionable error reports.

Related explainers

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps
typescript
import { useEffect, useState } from "react";
 
interface Section {
  id: string;

Building a scroll-spy hook in React

custom-hooks intersectionobserver dom-observation
Intermediate 8 steps
typescript
import { Injectable, Scope, Inject, NotFoundException } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';
import { DataSource } from 'typeorm';

Per-tenant database connections in NestJS

multi-tenancy connection-pooling dependency-injection
Advanced 8 steps

Share this explainer

Here's the card — post it anywhere.

Validating config with Zod schemas — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code