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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Zod schemas double as both runtime validators and the single source of truth for static types.
- 2refine lets you attach cross-field invariants that simple field types can't express.
- 3safeParse plus issue mapping turns raw validation failures into readable, actionable error reports.
Related explainers
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
typescript
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { catchError, filter, take, switchMap } from 'rxjs/operators';
Refreshing auth tokens in an Angular interceptor
http-interceptor
token-refresh
rxjs
Advanced
8 steps
typescript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; import { GqlExecutionContext } from '@nestjs/graphql'; import { Reflector } from '@nestjs/core'; import { JwtService } from '@nestjs/jwt';
How a GraphQL auth guard works in NestJS
authentication
authorization
jwt
Intermediate
7 steps
typescript
type ResizeCallback = (size: { width: number; height: number }) => void; export function observeResize(callback: ResizeCallback, delay = 150) { let timeoutId: ReturnType<typeof setTimeout> | undefined;
Debouncing window resize in TypeScript
debounce
closures
event-listeners
Intermediate
6 steps
typescript
import { Injectable, Logger, OnApplicationShutdown } from '@nestjs/common'; import { InjectRedis } from '@nestjs-modules/ioredis'; import Redis from 'ioredis'; import { DataSource } from 'typeorm';
Graceful shutdown hooks in NestJS
graceful-shutdown
lifecycle-hooks
dependency-injection
Intermediate
7 steps
typescript
import { Injectable, OnModuleInit, Logger } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Cron, CronExpression } from '@nestjs/schedule';
A self-refreshing feature flags provider in NestJS
caching
scheduled-tasks
dependency-injection
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/validating-config-with-zod-schemas-explained-typescript-ba72/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.