intermediate
Fastify schema validation
Use JSON schemas for validation, serialization, documentation, typed contracts, and early rejection of unsafe inputs.
Fastify attaches JSON Schema to routes for validation, serialization, and OpenAPI generation. Invalid requests fail before the handler runs; response schemas enable fast serialization via `fast-json-stringify`.
const createUser = {
schema: {
body: {
type: 'object',
required: ['email'],
properties: { email: { type: 'string', format: 'email' } },
additionalProperties: false,
},
response: {
201: {
type: 'object',
properties: { id: { type: 'string' } },
},
},
},
};
fastify.post('/users', createUser, async (req) => {
return { id: await service.create(req.body) };
});
Schemas cover `body`, `querystring`, `params`, and `headers`. `addSchema` registers reusable $ref fragments. Type providers (`@fastify/type-provider-typebox`) connect schemas to TypeScript inference.
On interviews: validation plus serialization performance, `additionalProperties: false` for strict contracts, and schema-driven documentation.
Common pitfalls: response schemas that do not match actual payloads (runtime errors), no shared $ref leading to drift, and validating only body while ignoring query params.
The trade-off is balancing simplicity, performance, safety, and operability — name which axis you optimized and what cost you accepted.
Checklist:
- Define route schemas for input and output.
- Reuse fragments with addSchema and $ref.
- Reject unknown properties on write endpoints.
- Align schemas with TypeScript via type providers.