Fastify Zod Validation
Use Zod with Fastify request validation, response schemas, type providers, JSON Schema conversion, and OpenAPI documentation without duplicating API contracts.
Quick answer: how do you use Zod with Fastify?
Use a Zod type provider when you want Fastify routes to infer request and response types from Zod schemas. Use Zod to JSON Schema conversion when Fastify should keep its JSON Schema validator, serializer, or OpenAPI pipeline as the runtime contract.
Fastify route with a Zod schema
Keep the boundary schema close to the route. Treat body, params, query, and response schemas as API contracts rather than loose TypeScript annotations.
import { z } from "zod";
const CreateUserBody = z.object({
email: z.string().email(),
role: z.enum(["admin", "member"]),
});
type CreateUserBody = z.infer<typeof CreateUserBody>;Validate body data before business logic
Even when Fastify route types are inferred, runtime validation should happen before the handler trusts unknown input. Use structured errors so clients receive predictable 400 responses.
fastify.post("/users", async (request, reply) => {
const parsed = CreateUserBody.safeParse(request.body);
if (!parsed.success) {
return reply.status(400).send({
error: "Invalid request body",
issues: parsed.error.flatten().fieldErrors,
});
}
return createUser(parsed.data);
});Response schema review
Fastify can validate and serialize responses through JSON Schema. If Zod owns the TypeScript contract, convert supported Zod response schemas to JSON Schema and review object strictness, optional fields, nullable fields, and enums.
const UserResponse = z.object({
id: z.string().uuid(),
email: z.string().email(),
role: z.enum(["admin", "member"]),
deletedAt: z.string().datetime().nullable(),
});
const userResponseJsonSchema = z.toJSONSchema(UserResponse);Type provider vs JSON Schema bridge
The type-provider path is ergonomic when Zod is the route source of truth. The JSON Schema bridge is better when Fastify serialization, OpenAPI, gateways, or non-TypeScript consumers need portable schemas.
- Choose a Zod type provider for developer experience and route inference.
- Choose JSON Schema output when the schema must be shared outside the TypeScript route.
- Keep custom refinements in Zod because JSON Schema cannot run arbitrary TypeScript callbacks.
OpenAPI documentation from Fastify Zod routes
If API docs are the goal, decide whether OpenAPI is generated from Zod, from converted JSON Schema, or from Fastify route schema objects. Mixing all three without ownership rules creates drift.
Fastify Zod failure modes
Most Fastify Zod issues are not syntax problems; they are ownership and conversion problems. Decide where parsing happens, which schema is source of truth, and how errors are mapped.
- Do not trust `request.body` as typed data until the runtime validator accepts it.
- Do not assume `refine` or `transform` survived a JSON Schema conversion.
- Do not publish OpenAPI docs from a schema that differs from route validation.
- Pin package versions when a type provider is part of the route contract.
Production checklist
A production Fastify Zod setup needs route tests, schema fixtures, and visible ownership of the contract.
- Test valid and invalid body, params, query, and response payloads.
- Add fixtures for nullable fields, enum drift, extra keys, missing required fields, and async validation.
- Confirm Fastify, Zod, and any type provider package versions are compatible.
- Request indexing only after the guide includes code that solves a real Fastify integration problem.
Fastify and Zod integration choices
| Workflow | Use it for | Tradeoff |
|---|---|---|
| fastify-type-provider-zod | Route typing and validation directly from Zod schemas. | Community package; confirm version compatibility with your Fastify release. |
| fastify-zod | Older package workflows that pair Zod models with Fastify and OpenAPI generation. | Package age and ecosystem fit need review before new production use. |
| Zod to JSON Schema | Converting Zod-owned schemas into Fastify's JSON Schema validation pipeline. | Custom refinements and transforms need a separate Zod validation step. |
| TypeBox or JSON Schema | Fastify-native schema validation and serialization. | Less direct if the rest of the app already uses Zod as source of truth. |
Use FrameworkKit to generate the starter code, then review the output before shipping it in production.
Zod to JSON Schema ConverterZod to JSON Schema resources
Zod to JSON Schema Converter
Use the canonical free online converter for Draft 2020-12, Draft 7, AJV, or OpenAPI-compatible output.
Zod to JSON Schema examples
Review object, enum, nullable, optional, array, and nested Zod conversion examples.
Zod to OpenAPI guide
Generate Swagger/OpenAPI docs from Zod schemas, compare package workflows, and choose OpenAPI 3.0 or 3.1.
Convert Zod to JSON Schema with AJV
Convert Zod to JSON Schema, choose an Ajv draft, compile validators, and avoid unsupported Zod features.
Zod to JSON Schema for OpenAPI
Publish OpenAPI-compatible schema output from TypeScript-owned Zod contracts.
Zod refine vs superRefine
Review why custom refinements cannot be represented as plain JSON Schema without a separate validation step.
Zod API schemas
Use Zod at API request and response boundaries before publishing or validating contracts.
Zod vs JSON Schema
Decide when Zod, JSON Schema, OpenAPI, and AJV should own runtime validation contracts.
FAQ
What is fastify-zod?
fastify-zod is a package name and search term for using Zod schemas with Fastify routes, validation, and OpenAPI-style workflows. Modern projects may also evaluate fastify-type-provider-zod.
Can Fastify validate Zod schemas directly?
Fastify is built around schema validation and serialization. Zod integration usually needs a type provider, a Zod-specific package, or conversion from Zod to JSON Schema.
Should Fastify use Zod or JSON Schema?
Use Zod when TypeScript application code owns the schema. Use JSON Schema when Fastify serialization, OpenAPI, gateways, or non-TypeScript systems need the contract.
Do Zod refinements work in Fastify JSON Schema output?
No. Custom refine and superRefine callbacks cannot be represented as plain JSON Schema. Keep them in a separate Zod validation step.
Related tools
JSON to Zod Converter
Convert JSON to Zod schemas with strict objects, optional field inference, and inferred TypeScript types.
TypeScript to Zod Converter
Convert TypeScript interfaces and type aliases into Zod schemas with inferred types in your browser.
OpenAPI to Zod
Turn OpenAPI schemas into Zod validators and lightweight typed fetch clients.