fastify-zod

Fastify Zod Validation

Use Zod with Fastify request validation, response schemas, type providers, JSON Schema conversion, and OpenAPI documentation without duplicating API contracts.

Zod to JSON Schema Converter

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

WorkflowUse it forTradeoff
fastify-type-provider-zodRoute typing and validation directly from Zod schemas.Community package; confirm version compatibility with your Fastify release.
fastify-zodOlder 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 SchemaConverting Zod-owned schemas into Fastify's JSON Schema validation pipeline.Custom refinements and transforms need a separate Zod validation step.
TypeBox or JSON SchemaFastify-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 Converter

Zod to JSON Schema resources

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