Skip to content
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.

Installation and configuration

npm install zod

No specific configuration file is required. Zod is imported directly into the files where validation is needed.

Use cases

Schema definition

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() ...

Validating API input in controller

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() 
    });
  }
};

Generating DTOs

With Fastify type providers

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,
  },
);

Using Zod for DTO of OpenAPI doc

// 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',
});

Using Zod in the frontend

Do's & Don'ts

โœ… 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.

Resources

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

๐Ÿ—๏ธ Architecture

๐ŸŒ Web Technologies

Backend

Frontend

๐Ÿ”ง Core Technologies

๐Ÿ” Security

โ›“๏ธ Blockchain

๐Ÿ› ๏ธ Dev Tools & Quality


๐Ÿ“ Page model

Clone this wiki locally