Fastify Type Provider Zod Serialization
Register a Zod type provider in Fastify so route schemas drive validation, serialization, and generated OpenAPI docs from one source.
Code
import Fastify from 'fastify';
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
import { z } from 'zod';
const app = Fastify({
logger: true,
}).withTypeProvider<ZodTypeProvider>();
const CreateOrderSchema = z.object({
body: z.object({
sku: z.string().min(3),
quantity: z.number().int().min(1).max(99),
}),
response: {
201: z.object({ id: z.string().uuid(), total: z.number() }),
400: z.object({ error: z.string() }),
},
});
app.post('/orders', { schema: CreateOrderSchema }, async (request, reply) => {
const { sku, quantity } = request.body;
if (sku === 'SOLD-OUT') {
return reply.code(400).send({ error: 'sku unavailable' });
}
return reply.code(201).send({
id: crypto.randomUUID(),
total: quantity * 19.9,
});
});
await app.listen({ port: 3000 });Report a problem with this exampleOpens a pre-filled issue on GitHub.