-
Notifications
You must be signed in to change notification settings - Fork 4
Zod
Francois edited this page Dec 19, 2025
·
1 revision
Presentation: Zod is a TypeScript-first schema declaration and validation library.
Key advantages of using Zod in the project are:
- Type Safety: Eliminates the need to duplicate type definitions. You declare a validator once and Zod infers the static TypeScript type.
- Runtime Validation: Ensures that data coming from the frontend (API body, query params) or external sources matches the expected format before processing.
- Developer Experience: Concise chainable interface and excellent autocomplete support.
npm install zodNo specific configuration file is required. Zod is imported directly into the files where validation is needed.
import { z } from "zod";
// Validation logic
export const UserProfileSchema = z.object({
id: z.number(),
username: z.string().min(3).max(20),
email: z.string().email(),
});
// Export type
export type UserProfile = z.infer<typeof UserProfileSchema>;Note
Conversion can be attempted with z.cocerce.string() (or any other type)
Tip
Use .strict() on object schemas if you want to forbid unknown keys in the request body.
Primitive types are
z.string()z.number()z.boolean()z.symbol()z.undefined()-
z.null()...
import { UserProfileSchema } from './dtos/user.dto';
export const updateUserProfile = (req: FastifyRequest, res: FastifyResponse) => {
const result = UserProfileSchema.safeParse(req.body);
if (!result.success) {
// result.error.format() returns a formatted error object
return res.status(400).json({
error: "Validation failed",
details: result.error.format()
});
}
};npm install fastify-type-provider-zod// index.ts
import {
serializerCompiler,
validatorCompiler,
ZodTypeProvider
} from 'fastify-type-provider-zod';
fastify.setValidatorCompiler(validatorCompiler);
fastify.setSerializerCompiler(serializerCompiler);
const app = fastify.withTypeProvider<ZodTypeProvider>();Example of schema
// schemas/friends.schema.ts
import { z } from 'zod';
// Validation Schema for input = classic Zod usage
export const addFriendInputSchema = z.object({
targetId: z.number({
required_error: "L'ID de l'ami est requis",
invalid_type_error: "L'ID doit รชtre un nombre",
}).int().positive(),
});
// Validation Schema for output = DTO
export const addFriendResponseSchema = z.object({
relationId: z.number(),
});Note
By convention we could suffix with InputSchema for controller input validation objects and ResponseSchema for controller output validation
usage in routes
// route.ts`
app.post(
'/users/friends',
{
schema: {
body: addFriendInputSchema,
response: {
201: addFriendResponseSchema,
},
},
addFriendHandler,
},
);// index.ts
// Register Swagger before routes
app.register(fastifySwagger, {
openapi: {
info: {
title: 'Transcendence API',
version: '1.0.0',
},
},
transform: jsonSchemaTransform,
});
app.register(fastifySwaggerUi, {
routePrefix: '/docs',
});| โ Do | โ Don't |
|---|---|
Use z.infer<typeof Schema> to generate Types. |
Write the TypeScript interface manually and separately from the validator. |
Use safeParse to handle validation errors gracefully. |
Use .parse() on user input (it throws an error and crashes if not caught). |
Use z.coerce for query parameters (e.g., ?page=1). |
Manually parse strings to numbers before validation. |
Centralize schemas in a dto or types folder. |
Define schemas inside the controller function scope repeatedly. |
| Type | Resource | Notes |
|---|---|---|
| ๐ | Official Documentation | Comprehensive API reference |
| ๐ฅ | Zod in 30 minutes | Quick crash course |
| ๐ป | Zod Playground | Test schemas in the browser |
| ๐ฆ | zod-validation-error | Helper to format error messages nicely |
| ๐ฆ | fastift-type-provider-zod | Bridge between Zod schemas and DTOs |
Legend: ๐ Doc, ๐ Book, ๐ฅ Video, ๐ป GitHub, ๐ฆ Package, ๐ก Blog
- Gateway Service - API Gateway & JWT validation
- Auth Service - Authentication & 2FA/TOTP
- AI Service - AI opponent
- API Documentation - OpenAPI/Swagger
- DB Schema - Databases
- Fastify - Web framework
- Prisma - ORM
- WebSockets - Real-time communication
- Restful API - API standards
- React - UI library
- CSS - Styling
- Tailwind - CSS framework
- Accessibility - WCAG compliance
- TypeScript - Language
- Zod - Schema validation
- Nginx - Reverse proxy
- Logging and Error management - Observability
- OAuth 2.0 - Authentication flows
- Two-factor authentication - 2FA/TOTP
- Avalanche - Blockchain network
- Hardhat - Development framework
- Solidity - Smart contracts language
- Open Zeppelin - Security standards
- ESLint - Linting
- Vitest - Testing
- GitHub Actions - CI/CD
- Husky, Commit lints and git hooks - Git hooks
- ELK - Logging stack
๐ Page model