How does a Fastify type provider turn one schema into typed routes?
A type provider is a TypeScript-only adapter. It tells Fastify's generics how to turn a schema object into a static type. Calling withTypeProvider<Provider>() on the instance returns the same server with different type parameters. After that, every route infers request.body, request.query, request.params, request.headers and the reply payload directly from its schema option. Nothing changes at runtime: validation still runs through whatever validator compiler is registered. The provider only makes the compiler sees and the type the handler sees come from the same object.
This replaces the older pattern of writing a JSON Schema and a matching interface, then passing the interface through route generics like Body and Querystring. That pattern compiles even when the two drift apart, so a field renamed in the schema but not the interface surfaces as a runtime surprise. With a provider there is only one definition, so drift is impossible.
Consider the same route, POST /users/:id, in both libraries:
- TypeBox: you build
paramsandbodywithType.Object(...), which produces plain JSON Schema. You registerTypeBoxTypeProvider, and Fastify's default Ajv-based compiler validates it unchanged. - Zod: you write
z.object(...)schemas and registerZodTypeProvider. You also set the package's validator and serializer compilers, because Ajv cannot execute a Zod schema.
In both cases, request.params.id and request.body.email are typed without annotations.
The limit is that types only cover what the schema declares. Headers you don't list keep Fastify's default loose header typing. If a route has no response schema, the reply payload is not checked against any contract.
import Fastify from 'fastify';
import { Type } from '@sinclair/typebox';
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import { z } from 'zod';
import {
ZodTypeProvider,
validatorCompiler,
serializerCompiler,
} from 'fastify-type-provider-zod';
// TypeBox: Type.Object() emits plain JSON Schema, so the default Ajv compiler validates it as-is.
const tb = Fastify().withTypeProvider<TypeBoxTypeProvider>();
tb.post('/users/:id', {
schema: {
params: Type.Object({ id: Type.String() }),
body: Type.Object({ email: Type.String({ format: 'email' }) }),
response: { 200: Type.Object({ id: Type.String(), email: Type.String() }) },
},
}, async (request) => {
// Inferred from the schema: id and email are typed as string, no interface or generics needed.
return { id: request.params.id, email: request.body.email };
});
// Zod: Ajv cannot run a Zod schema, so register the package's compilers before defining routes.
const zd = Fastify().withTypeProvider<ZodTypeProvider>();
zd.setValidatorCompiler(validatorCompiler);
zd.setSerializerCompiler(serializerCompiler);
zd.post('/users/:id', {
schema: {
params: z.object({ id: z.string() }),
body: z.object({ email: z.string().email() }),
response: { 200: z.object({ id: z.string(), email: z.string() }) },
},
}, async (request) => {
// request.headers is not declared in either schema, so it keeps Fastify's loose default typing.
return { id: request.params.id, email: request.body.email };
});
The same POST /users/:id route defined with TypeBox and with Zod, where withTypeProvider makes each schema drive both runtime validation and the static types of params, body and the 200 reply.
How do TypeBox and Zod differ inside Fastify's validation and serialization pipeline?
The difference starts with what each library produces. A TypeBox builder returns a plain JSON Schema object. Fastify does not need to know TypeBox exists. The request schemas go to the default Ajv validator, which compiles them into validation functions at startup. The response schemas go to fast-json-stringify, which compiles a serializer for each status code. The type provider only affects the compiler's view of the types. At runtime, Fastify sees standard JSON Schema.
A Zod schema is a JavaScript object with its own parse logic, not JSON Schema. Ajv cannot run it. A Zod type provider therefore has to replace both validatorCompiler and serializerCompiler, which moves request validation and response serialization out of Ajv and fast-json-stringify and into Zod. Fastify's hooks and lifecycle stay the same. The engine that checks and shapes data is different.
What reaches the client
fast-json-stringify builds output from the declared schema, not from the object you pass it. Properties the schema does not list are dropped, unless the schema allows additional properties. This is part of why it is faster than JSON.stringify. It also means a passwordHash field on a database row never reaches the client if the response schema omits it.
With a Zod serializer, filtering depends on how the object schema treats unknown keys. Zod's default object mode strips them. A passthrough or loose object keeps them, and a strict object throws instead. The serializer implementation also affects the result. Write a test that returns an object with an extra field and checks that the field is removed.
Either way, response filtering is a safety net. Authorization decisions belong in your handlers and data layer, not in the response schema.
TypeBox path Zod type provider path
+-------------------------+ +-------------------------+
| Type.Object({...}) | | z.object({...}) |
| = plain JSON Schema | | = Zod object, own parse |
+------------+------------+ +------------+------------+
| |
v v
+-------------------------+ +-------------------------+
| Fastify default | | validatorCompiler |
| validatorCompiler: Ajv | | replaced -> Zod parse |
| (compiled at startup) | | |
+------------+------------+ +------------+------------+
| |
v v
+---------------+ +---------------+
| handler | | handler |
+-------+-------+ +-------+-------+
| { id, email, passwordHash } |
v v
+-------------------------+ +-------------------------+
| fast-json-stringify | | serializerCompiler |
| per status code; emits | | replaced -> Zod |
| only declared props | | strip: extra dropped |
| | | loose: extra kept |
| | | strict: throws |
+------------+------------+ +------------+------------+
| |
v v
{ id, email } depends on mode -> TEST IT
Either path: response filtering is a safety net, not access control.
TypeBox hands plain JSON Schema to Fastify's default Ajv validator and fast-json-stringify, which emits only declared properties, while a Zod type provider replaces both compilers so whether extra fields like passwordHash are stripped depends on the object's unknown-key mode.
How do you implement coercion, defaults and shared schemas with each library?
A pagination query is a good test because every value in a query string arrives as text. With TypeBox, you declare limit as Type.Integer({ minimum: 1, maximum: 100, default: 20 }) and cursor as an optional string. Ajv then coerces "5" to 5 and fills in a missing limit before your handler runs. This only works if coercion and defaults are enabled. Fastify passes its own Ajv configuration, and many projects override it, so check the ajv.customOptions your server actually uses.
Zod does not coerce anything implicitly. z.number() rejects "5", so the query schema needs z.coerce.number().int().min(1).max(100).default(20). That is more verbose, but the coercion is visible at each field. Watch z.coerce.boolean(): it uses JavaScript truthiness, so "false" becomes true.
Decide where coercion belongs. Query strings and path params need it. Bodies usually should not. A client that sends "price": "10" in JSON has a bug, and silent coercion hides it until another consumer breaks.
For shared schemas in TypeBox, give each schema an $id and register it with fastify.addSchema. Routes then reference it with Type.Ref, which emits $ref, and Ajv compiles it once. The Zod equivalent is an ordinary module that exports schema constants. Routes import them, and you compose variants with .extend or .pick.
Finally, give clients one error shape from both libraries. In setErrorHandler, map each library's errors into the same structure:
- Ajv: read
error.validation, usinginstancePathandmessagefor each entry. - Zod: read the issues from your type provider's error, using
pathandmessagefor each entry.
Convert both into { code, field, message } entries so clients never depend on which validator produced them.
import Fastify from 'fastify';
import { Type } from '@sinclair/typebox';
import { z, ZodError } from 'zod';
// Set Ajv options explicitly instead of relying on whatever defaults are in effect.
const app = Fastify({ ajv: { customOptions: { coerceTypes: true, useDefaults: true } } });
// TypeBox: register once with an $id, reference it by $ref from any route.
const Pagination = Type.Object({
limit: Type.Integer({ minimum: 1, maximum: 100, default: 20 }),
cursor: Type.Optional(Type.String()),
}, { $id: 'Pagination' });
app.addSchema(Pagination);
app.get('/orders', { schema: { querystring: Type.Ref('Pagination') } }, async (req) => req.query);
// Zod: a shared module of exported schemas; coercion is opt-in per field.
export const ZPagination = z.object({
limit: z.coerce.number().int().min(1).max(100).default(20),
cursor: z.string().optional(),
});
export const ZOrderQuery = ZPagination.extend({ status: z.enum(['open', 'closed']).optional() });
// Bodies use plain z.number(): a JSON "10" for a number is a client bug, so reject it.
// One error shape for clients, whichever validator failed.
app.setErrorHandler((error, _req, reply) => {
if (error.validation) { // Ajv
const errors = error.validation.map((e) => ({
code: 'invalid_field', field: e.instancePath || '/', message: e.message ?? 'invalid' }));
return reply.status(400).send({ errors });
}
// Assumes the Zod issues reach here as a ZodError; check how your type provider surfaces them.
if (error instanceof ZodError) {
const errors = error.issues.map((i) => ({
code: 'invalid_field', field: '/' + i.path.join('/'), message: i.message }));
return reply.status(400).send({ errors });
}
reply.status(500).send({ errors: [{ code: 'internal', field: null, message: 'Internal error' }] });
});
A pagination query defined as a shared TypeBox schema registered with $id, addSchema and Type.Ref, the same contract as an exported Zod module with explicit z.coerce fields, and one setErrorHandler that maps Ajv and Zod failures into a single { code, field, message } shape.
When should you use Zod instead of TypeBox for Fastify routes?
Choose Zod when the schema already exists somewhere else in your codebase. If your frontend validates forms with Zod and imports request shapes from a shared package, a Zod type provider lets the backend enforce the same definitions. You then have one source of truth instead of a Zod copy and a JSON Schema copy that drift apart.
Zod also fits routes where validation is really parsing. Transforms can turn an ISO string into a Date, trim and lowercase an email, or normalize a phone number. Refinements can check rules that span fields, such as endDate falling after startDate, and you can attach a custom message to each rule. Because Zod separates input and output types, the handler receives the transformed shape, not the raw wire format.
Ajv, which TypeBox schemas run through, validates data. Beyond type coercion and defaults, it does not reshape it. TypeBox users therefore move transformation into a preHandler hook or into the handler itself, and must keep the declared type in sync with what that code produces by hand.
Choose TypeBox when the contract has to outlive TypeScript. A TypeBox schema is standard JSON Schema, so these consumers can read it directly without a conversion step:
- OpenAPI generators
- contract-testing tools
- services written in Go, Python or Java
Converting Zod to JSON Schema works for plain shapes. Transforms and refinements, however, have no faithful JSON Schema equivalent, so they are dropped or approximated. Non-TypeScript consumers then see a looser contract than the one your server actually enforces.
import Fastify from 'fastify';
import { z } from 'zod';
import {
serializerCompiler,
validatorCompiler,
type ZodTypeProvider,
} from 'fastify-type-provider-zod';
// In a real codebase this would be imported from a package shared with the frontend.
export const BookingBody = z
.object({
email: z.string().trim().toLowerCase().email(), // normalize before the handler sees it
startDate: z.string().datetime().transform((s) => new Date(s)), // ISO string in, Date out
endDate: z.string().datetime().transform((s) => new Date(s)),
})
// Cross-field rule with a custom message. Plain JSON Schema cannot express this.
.refine((b) => b.endDate > b.startDate, {
message: 'endDate must be after startDate',
path: ['endDate'],
});
// Input and output types differ: the client sends strings, the handler receives Dates.
type BookingInput = z.input<typeof BookingBody>; // { startDate: string; ... }
type BookingParsed = z.output<typeof BookingBody>; // { startDate: Date; ... }
const app = Fastify();
app.setValidatorCompiler(validatorCompiler);
app.setSerializerCompiler(serializerCompiler);
app.withTypeProvider<ZodTypeProvider>().post(
'/bookings',
{ schema: { body: BookingBody } },
async (req) => {
// req.body is the parsed output, so no manual Date conversion or trimming here.
const ms = req.body.endDate.getTime() - req.body.startDate.getTime();
return { email: req.body.email, nights: Math.round(ms / 86_400_000) };
},
);
A Fastify route using a Zod type provider, where transforms normalize the email and turn ISO strings into Dates, and a refinement enforces a cross-field date rule, so the handler receives the parsed output type instead of the raw wire format.
When should you avoid each approach?
Each library has failure modes that only show up once the contract grows.
Avoid TypeBox-only when the contract depends on transforms, async checks such as "username not taken", or cross-field rules like "endDate must follow startDate." JSON Schema can't express these well. Your options are Ajv custom keywords or ad-hoc checks in handlers. Custom keywords are code that someone has to maintain, test against Ajv upgrades, and teach to new team members. Handler checks quietly split the contract across two places.
Avoid Zod when you rely on fast-json-stringify to strip undeclared fields from responses, which is a cheap safeguard against leaking internal properties. Also avoid it when you need generated OpenAPI that is accurate, or when you want fewer adapters that must keep pace with Fastify upgrades. The converted JSON Schema describes shape only. Refinements and transforms are missing, so the published spec is looser than what runtime enforces. Check the generated output for how it handles $refs, nullable fields and unions, because these are the places converters most often produce output you didn't intend.
| Avoid… | When | Why |
|---|---|---|
| TypeBox-only | Transforms, async or cross-field rules | These need Ajv custom keywords or handler code |
| Zod | Response field filtering, strict OpenAPI | The spec omits runtime-only rules, and the adapter is another dependency to keep in sync |
| Either | Deeply composed schemas | Slow type-checking and errors that are hard to read |
In both libraries, heavily nested generics and intersections can slow TypeScript type-checking noticeably. They also produce compiler errors that are hard to trace back to the field that caused them. Flatten shared schemas and name the intermediate types so errors point somewhere useful.
What are the alternatives, and how do the options compare on cost?
| Option | Validator | Response serialization and filtering | Coercion defaults | OpenAPI path | Error shape | Client sharing | Transforms | Maintenance burden |
|---|---|---|---|---|---|---|---|---|
| TypeBox + type provider | Fastify's built-in Ajv | Fast compiled serializer; drops undeclared fields | Fastify's Ajv defaults apply | Swagger tooling reads schemas as-is | Fastify's standard 400 | Possible, uncommon on frontends | Not applied by Ajv | Low |
| Zod + type provider | Zod, via adapter compilers | Zod parse, then plain stringify | Explicit, per field | Needs a transform step | Zod issues, usually reformatted | Natural fit | Native | Adapter upkeep |
| JSON Schema + hand-written interfaces | Built-in Ajv | Fast compiled serializer | Fastify's Ajv defaults apply | Direct | Fastify's standard 400 | Manual | None | Interface drift |
| No schema | None | Plain stringify; leaks extra fields | None | Hand-written spec | Whatever handlers throw | None | In handlers | Highest |
Most engineering time is saved by having a single definition. Hand-written interfaces drift from their JSON Schema without any error. The compiler accepts a handler that returns a field the serializer strips, and the gap only shows up as a client bug.
TypeBox has the shortest path to documentation because swagger tooling consumes its output with no conversion. Zod costs less when the frontend already imports the same schemas: you avoid writing the contract twice and avoid a sync step between the two copies.
Ongoing cost lives in glue code. Zod adapters have to keep pace with both Fastify and Zod releases. Custom Ajv keywords need their own tests and their own documentation mappings. Choose the option with the least glue that still covers your clients.
How do you mix, migrate and benchmark TypeBox and Zod in one service?
Fastify makes mixing possible because setValidatorCompiler and setSerializerCompiler follow plugin encapsulation. Register a Zod-based plugin, set the Zod adapter's compilers inside it, and only routes in that plugin's scope use them. Sibling plugins keep the default Ajv and fast-json-stringify path for TypeBox. Individual routes can also override with validatorCompiler and serializerCompiler options. Use that override rarely. A per-route exception is invisible when you read the plugin.
Unmanaged mixing gives clients two error shapes and gives engineers two mental models. Before you migrate, set three rules:
- One error formatter. Register a single
setErrorHandlerat the root. Have it normalize both Ajv errors and Zod issues into the same response body, with the same status code and field paths. - A written coercion policy. Ajv's
coerceTypesand Zod's explicitz.coercebehave differently for querystrings. Decide per input location (query, params, body) whether strings become numbers, and test that both stacks agree. - Boundaries by plugin, not by route. For example, "the
/billingplugin uses Zod for its transforms, everything else uses TypeBox." Record the boundary in the plugin's README.
To benchmark, pick one representative route and build it twice. Use the same handler, a realistic request body (nested objects, arrays, optional fields), and a realistic response. First, time the compiled validator and serializer functions directly in a loop. Then load the full route with an HTTP load generator on your own hardware, with logging disabled.
Illustrative estimate: if validation and serialization take 5% of request time, a validator that is twice as fast saves about 2.5%. Measure on your own route before you decide whether that matters.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to fastify typebox vs zod, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.