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 });Inside the snippet
Await points sequence the asynchronous work; a rejection lands at the awaiting line. From fastify it pulls z — the imports name exactly which library surface the snippet touches.
Top-level bindings app, CreateOrderSchema hold the demo state — nothing sits inside a function scope.
Watch out for
- Dependency check:
fastify,fastify-type-provider-zodandzod— not built-in, must be present in the project. - This is browser-side code —
cryptowill not resolve in Node. - The guard
sku === 'SOLD-OUT'short-circuits the flow with an earlyreturnwhen its condition holds.
Core lines
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 });
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Do I need to install anything before running this?
- Yes: `fastify`, `fastify-type-provider-zod` and `zod` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.