Typorithm · medium

Validation & Schemas

validation-schemasnodejsvalidationzodschema
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Validation & Schemas

0%

API Patterns

Validate untrusted input at the boundary with a schema library like Zod: define the expected shape, then parse to get a typed, validated object or a thrown error. Never trust req.body directly; frameworks like Fastify and Hono also support JSON-schema validation natively.

Anything from the network — req.body, query params, headers — is untrusted. Validate it at the boundary before it reaches your business logic, rather than scattering manual checks.

A schema library like Zod lets you declare the expected shape once: z.object with typed fields and refinements such as .email(), .int(), and .positive(). The schema is the single source of truth for the input.

Calling schema.parse(req.body) returns a fully typed, validated object, or throws a detailed error if the data does not match. Frameworks like Fastify and Hono can also validate against JSON Schema natively.

01

Validate untrusted input at the boundary, not deep in code.

02

z.object defines the expected shape; refinements add constraints.

03

parse returns a typed object or throws on invalid input.

import { z } from "zod";
const UserSchema = z.object({
  email: z.string().email(),
  age: z.number().int().positive(),
});
const user = UserSchema.parse(req.body);

Read the implementation

Connect each part of the code to the concept before you type.

1. Import Zod

z is Zod's schema builder, the entry point for declaring expected shapes.

import { z } from "zod";

2. Define a schema

z.object describes the expected shape of an object — its keys and their types.

const UserSchema = z.object({

3. String with format

Chained refinements like .email() add constraints beyond the base type.

email: z.string().email(),

4. Number constraints

age must be a number that is also an integer and positive — constraints compose.

age: z.number().int().positive(),

5. Parse input

parse validates req.body and returns a typed object, or throws if the data is invalid.

const user = UserSchema.parse(req.body);

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Validation & Schemas: Lesson & Practice · Typorithm | ApplyDjinn