1. Import Zod
z is Zod's schema builder, the entry point for declaring expected shapes.
import { z } from "zod";Typorithm · medium
Step 1 of 8 · intro card
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.
Validate untrusted input at the boundary, not deep in code.
z.object defines the expected shape; refinements add constraints.
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);Connect each part of the code to the concept before you type.
z is Zod's schema builder, the entry point for declaring expected shapes.
import { z } from "zod";z.object describes the expected shape of an object — its keys and their types.
const UserSchema = z.object({Chained refinements like .email() add constraints beyond the base type.
email: z.string().email(),age must be a number that is also an integer and positive — constraints compose.
age: z.number().int().positive(),parse validates req.body and returns a typed object, or throws if the data is invalid.
const user = UserSchema.parse(req.body);Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.