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.

TypescriptNodeForm Validation

Code

typescriptsnippet
32 lines
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-zod and zod — not built-in, must be present in the project.
  • This is browser-side code — crypto will not resolve in Node.
  • The guard sku === 'SOLD-OUT' short-circuits the flow with an early return when 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

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.