One schema, three jobs: validation, types and OpenAPI from TypeBox
Define each request and response shape once. Get runtime validation, compile-time types and the OpenAPI document from the same object, with CI to prove it.
Take a field that gets renamed from displayName to name. The TypeScript interface is updated, because the compiler insists. The handler is updated, because the tests insist. The validation rules live in another file that nobody opens, so they still demand displayName, and the first client to send the new shape gets a 400 that mentions a field it has never heard of. Meanwhile the OpenAPI document that a generated SDK is built from still describes the old name, because it is edited by hand when someone remembers.
That is one fact (the shape of a note, a user, an order) written down three times, in three formats that cannot check each other. This walkthrough writes it once, with TypeBox and Fastify: one schema object that validates requests at runtime, infers the TypeScript type at compile time and emits the OpenAPI document, plus a CI check that keeps the committed spec honest. The same schema then validates data that never arrives over HTTP, which is where it earns a lot of its keep. The examples assume Node 22, Fastify 5 and the typebox 1.x package.
Why the schema library is the choice that matters#
The OpenAPI-first route, where the spec is the input and code is generated from it, is the right answer if another team authors the contract. Its weak point is that the spec becomes a hand-edited source file, the situation described in an OpenAPI gateway spec you never edit by hand. Generating the spec from code that the compiler and the tests already police removes that class of drift.
Zod is a good choice too. Zod 4 has a native z.toJSONSchema(), and its target option accepts "openapi-3.0", as the Zod documentation describes. What decides it in a Fastify service is that Fastify consumes JSON Schema directly. A TypeBox schema already is a JSON Schema object, so there is no conversion step between the thing that validates and the thing that is documented.
TypeBox describes itself as a runtime type system that creates in-memory JSON Schema objects. Each builder call returns a plain object that is valid JSON Schema and also carries a TypeScript type, extracted with Static. Fastify validates each part of a request (body, querystring, params, headers) against the schema attached to the route, using Ajv. @fastify/swagger reads those same route schemas and turns them into an OpenAPI document.
Define the shapes in a module that knows nothing about HTTP#
TypeBox 1.x is published as the typebox package. The older @sinclair/typebox 0.34 line still exists, but the Fastify provider declares typebox as a peer dependency, so install that one:
npm install fastify @fastify/swagger @fastify/type-provider-typebox typeboxThe schemas get their own module with no Fastify import, which matters later when a queue consumer imports them.
import Type, { type Static } from "typebox";
export const CreateNote = Type.Object({
title: Type.String({ minLength: 1, maxLength: 120 }),
body: Type.String({ maxLength: 10_000 }),
tags: Type.Optional(Type.Array(Type.String({ maxLength: 24 }), { maxItems: 5 })),
});
export const Note = Type.Object({
id: Type.String({ format: "uuid" }),
title: Type.String(),
body: Type.String(),
tags: Type.Array(Type.String()),
createdAt: Type.String({ format: "date-time" }),
});
export type CreateNoteInput = Static<typeof CreateNote>;
export type NoteOutput = Static<typeof Note>;Type.Optional keeps tags out of the emitted required list and makes it string[] | undefined in the inferred type, so schema and type cannot disagree about it. Constraints such as minLength and maxItems travel with the schema into both validation and the OpenAPI output. The request is documented because it is enforced, not the other way round. I lean on the bounds in particular (lengths, ranges, enum membership, array sizes): rejecting a pathological payload at the door is far cheaper than discovering it in a database bill.
Wire the schemas into Fastify so handlers need no types#
The type provider is attached when the instance is created. The provider's README warns that calling withTypeProvider on a separate line afterwards does not work, so chain it on the constructor.
import Fastify from "fastify";
import swagger from "@fastify/swagger";
import type { TypeBoxTypeProvider } from "@fastify/type-provider-typebox";
import { randomUUID } from "node:crypto";
import { registerErrorShape } from "./errors.ts";
import { CreateNote, Note } from "./schemas.ts";
export async function buildApp() {
const app = Fastify().withTypeProvider<TypeBoxTypeProvider>();
registerErrorShape(app);
await app.register(swagger, {
openapi: { openapi: "3.0.3", info: { title: "Notes API", version: "1.0.0" } },
});
app.post(
"/notes",
{ schema: { body: CreateNote, response: { 201: Note } } },
async (req, reply) => {
const { title, body, tags = [] } = req.body; // typed from CreateNote
return reply.code(201).send({
id: randomUUID(),
title,
body,
tags,
createdAt: new Date().toISOString(),
});
},
);
return app;
}Nothing in the handler declares a type. req.body is inferred from CreateNote, and reply.send in a route with a 201 response schema is checked against Note. Change Note.createdAt to Type.Integer() and the toISOString() call stops compiling: that is the compile-time job. An empty title is rejected with a 400, and so are six tags, because both violate constraints in the schema: that is the runtime job.
Two ordering rules. Register @fastify/swagger before the routes, because its README says routes registered earlier will not appear in the document. And set the error handler before the routes too, because a route picks up the handler that exists when it is added. That is why registerErrorShape(app) comes first above.
Know exactly what Fastify's validator does to your input#
Fastify's validation reference lists the default Ajv options as coerceTypes: 'array', useDefaults: true, removeAdditional: true and allErrors: false. Four consequences follow, and the first one is easy to get wrong.
- Unknown properties are removed only when the schema forbids them. The reference describes
removeAdditional: trueas removing additional properties ifadditionalPropertiesis set tofalse. A schema without that keyword leaves extra properties inreq.bodyuntouched.CreateNoteabove does not forbid them, so{ "title": "t", "body": "b", "extra": 1 }passes andextrais still there. With{ additionalProperties: false }on the object, the extra property is silently deleted and the request still succeeds. Neither setting rejects anything. - Types are coerced. A string
"5"in a querystring parameter declared as an integer becomes the number 5. Convenient for querystrings, surprising for JSON bodies, whereType.Integer()accepts the string"42"too. - Defaults are applied from
defaultkeywords in the schema. allErrorsstays false. The Fastify docs say to leave it that way, since turning it on makes a denial-of-service attack possible. Clients get the first problem found, not all of them.
The handler above destructures three fields, and the 201 response schema strips anything else on the way out, so a request test against /notes cannot show what the validator did to the body. To see it, use routes that report what they received:
import { test } from "node:test";
import assert from "node:assert/strict";
import Fastify from "fastify";
import Type from "typebox";
import type { TypeBoxTypeProvider } from "@fastify/type-provider-typebox";
const Loose = Type.Object({ title: Type.String() });
const Strict = Type.Object({ title: Type.String() }, { additionalProperties: false });
const Seen = Type.Object({ keys: Type.Array(Type.String()) });
function echoApp() {
const app = Fastify().withTypeProvider<TypeBoxTypeProvider>();
app.post("/loose", { schema: { body: Loose, response: { 200: Seen } } }, async (req) => ({
keys: Object.keys(req.body),
}));
app.post("/strict", { schema: { body: Strict, response: { 200: Seen } } }, async (req) => ({
keys: Object.keys(req.body),
}));
return app;
}
test("extra properties survive unless the schema forbids them", async () => {
const app = echoApp();
const payload = { title: "t", extra: 1 };
const loose = await app.inject({ method: "POST", url: "/loose", payload });
assert.deepEqual(loose.json().keys.sort(), ["extra", "title"]);
const strict = await app.inject({ method: "POST", url: "/strict", payload });
assert.equal(strict.statusCode, 200);
assert.deepEqual(strict.json().keys, ["title"]);
});If you want strict rejection instead of silent removal, turn the removal off so that additionalProperties: false produces a 400. Fastify accepts Ajv options through its constructor, and removeAdditional: false is a valid setting:
const app = Fastify({ ajv: { customOptions: { removeAdditional: false } } })
.withTypeProvider<TypeBoxTypeProvider>();For public write endpoints I prefer this. A client that misspells an optional field then learns about it immediately, instead of getting a success response and no effect.
Response schemas have a separate job. With an output schema present, Fastify serialises with fast-json-stringify, and the docs say that helps prevent accidental disclosure of sensitive information: a handler that returns { a: "ok", secret: "leak" } through a 200 schema that declares only a sends {"a":"ok"}. Treat that as a safety net, not a design tool. The compile-time check on reply.send is the one that tells you early.
Even so, I declare a response schema on every route in my services, because the narrowness works as an allowlist. When an internal field such as a moderation flag or an internal score is added to a stored record later, it does not leak into a public response by default; the contract names what goes out, not whatever the object happened to contain. I apply the same thinking to writes: update endpoints accept named fields, never a whole object to merge, which is the difference between an API and a mass-assignment vulnerability with documentation.
Give validation errors a shape clients can parse#
The default 400 body is fine in development. For a public API a stable error contract matters, because clients end up parsing it. Fastify exposes validation failures on the error object (validation and validationContext) and lets you set an error handler:
import type { FastifyError, FastifyInstance } from "fastify";
export function registerErrorShape(app: FastifyInstance) {
app.setErrorHandler((err: FastifyError, req, reply) => {
if (err.validation) {
return reply.code(400).send({
error: "invalid_request",
where: err.validationContext, // "body", "querystring", "params" or "headers"
problems: err.validation.map((v) => ({
path: v.instancePath || "/",
message: v.message ?? "invalid",
})),
});
}
req.log.error({ err }, "unhandled error");
const status = err.statusCode && err.statusCode < 500 ? err.statusCode : 500;
return reply.code(status).send({ error: "internal" });
});
}An empty title now produces {"error":"invalid_request","where":"body","problems":[{"path":"/title","message":"must NOT have fewer than 1 characters"}]}, with the message wording coming from Ajv. Naming the field and the constraint turned a whole class of frontend debugging sessions ("why is this 400ing?") into a five-second read for me.
Emit the OpenAPI document and let CI guard it#
Once the app is ready, app.swagger() returns the document as an object. A small script writes it to a file that is committed:
import { writeFileSync } from "node:fs";
import { buildApp } from "../src/app.ts";
const app = await buildApp();
await app.ready();
writeFileSync("openapi.json", JSON.stringify(app.swagger(), null, 2) + "\n");
await app.close();The generated document contains exactly the constraints from the schemas: minLength: 1 and maxLength: 120 on the title, maxItems: 5 on tags, the uuid and date-time formats on the response. Nobody typed them twice. CI regenerates the file and fails when the committed copy is stale:
node scripts/emit-openapi.ts
git diff --exit-code -- openapi.jsonNode can run TypeScript files directly through type stripping. It needs the --experimental-strip-types flag on early Node 22 releases and is on by default in later ones, so check the Node.js TypeScript documentation for the version you run, or use tsx or a compile step if you would rather not depend on it.
The pull request now shows the contract change as a diff. A reviewer who sees maxItems: 5 become maxItems: 50 knows a limit moved, even if the code diff was a one-line change in a schema file. That visibility is half the value. It also shows the cost of a Fastify, type provider or TypeBox upgrade: they declare peer dependencies on each other, so upgrade them together and let the diff tell you whether the emitted spec changed.
It also changed how I work: I write the schema before the handler. That forces the questions that matter (what is required, what are the bounds, what does the error surface look like) while they are still design questions rather than migration projects, and in review I read the contract diff first, so I know the blast radius before I read any implementation.
If the document feeds Google Cloud API Gateway, check which OpenAPI version your configuration expects. @fastify/swagger emits Swagger 2.0 when configured with its swagger option instead of openapi. Gateway-specific extensions belong in a generator step, not in route schemas.
Reuse the same schema where there is no HTTP#
A queue consumer, a webhook receiver and a job that reads stored documents all handle data you did not produce a moment ago. The same schema object validates them with TypeBox's value API:
import Value from "typebox/value";
import { CreateNote, type CreateNoteInput } from "./schemas.ts";
export function parseNoteMessage(raw: string): CreateNoteInput {
const candidate: unknown = JSON.parse(raw);
if (!Value.Check(CreateNote, candidate)) {
const problems = [...Value.Errors(CreateNote, candidate)].map(
(e) => `${e.instancePath || "/"} ${e.message}`,
);
throw new Error(`invalid message: ${problems.join("; ")}`);
}
return candidate; // narrowed to CreateNoteInput
}Value.Check is a type guard, so after the if the compiler knows the shape. Value.Errors returns the failures, each with an instancePath and a message. Unlike Fastify's route validation, Value.Check neither coerces nor removes anything: an object with an extra key passes and keeps the key. For messages that end up in a dead-letter queue when invalid, as in dead-letter queues: a small team's safety net, the error text above is what you want in the log, not a stack trace from deep inside a handler.
What the single schema does not give you#
The builder is a second syntax. Type.Optional(Type.Array(...)) reads worse than tags?: string[] to someone seeing it for the first time. The inferred type is the readable form and editors show it on hover, but it is a real onboarding cost.
Format keywords depend on the validator. format: "uuid" and format: "date-time" are enforced because the validator in use implements them. Another consumer of the same JSON Schema, such as a client-side validator or a documentation tool, may treat formats as annotations only. Do not make a security decision depend on a format being enforced somewhere you do not control.
Coercion changes meaning. If a field is an identifier that must stay a string, declare it as a string with a pattern, not as an integer, so that coercion cannot reinterpret it.
The spec describes what the code accepts, not what the product intends. It cannot say that a field is deprecated, that an endpoint is rate limited, or what an error means. TypeBox lets you attach description and examples to any schema so they land in the document, and someone still has to write them.
A legacy corner will survive. Two of my older services still use Joi, from an earlier stage of the codebase. It works and it is tested, and rewriting it would be motion without progress. What keeps that sane is containment: the old pattern may not spread, every new service and endpoint uses TypeBox, and the old corner shrinks by attrition, one natural refactor at a time. The failure is not having such a corner but letting "that is how service X does it" pass for precedent.
It is not the answer to every contract. If another team owns the contract and hands you an OpenAPI file, generate types from it and treat it as the source of truth rather than rebuilding it in TypeBox by hand. With three endpoints and one client that you also own, plain TypeScript types plus a single validator may be enough. And if your framework does not consume JSON Schema, the idea still applies, but you will need an adapter, at which point a library with a native adapter for that framework may fit better.
Related articles
All articles →Per-service path fragments, a small Node generator that enforces the rules humans forget, and a CI check that keeps the API Gateway config honest.
13 min
Pub/Sub will deliver some messages twice, and that is by design. Here is how to build consumers whose side effects happen once anyway, with working code.
13 min
A practical split for small teams: coarse per-client limits at the edge, per-user and per-cost limits in the service, and the 429 behaviour both must share.
11 min