Validate requests and serialise responses with JSON Schema, TypeBox, AJV, fast-json-stringify, and Fastify's encapsulation model
0 / 5 completed
1 / 5
How does Fastify use JSON Schema on route definitions?
Fastify schema validation: Example: fastify.post('/user', { schema: { body: { type: 'object', required: ['name'], properties: { name: { type: 'string' } } } } }, handler). Fastify compiles the schema with AJV on startup. Invalid bodies return a structured 400 with validation error details. The response schema drives fast JSON serialisation via fast-json-stringify.
2 / 5
What is TypeBox in the context of Fastify?
TypeBox:import { Type, Static } from '@sinclair/typebox'. Define const UserSchema = Type.Object({ name: Type.String() }). Use it as the Fastify schema (it produces valid JSON Schema) and as a TypeScript type via type User = Static<typeof UserSchema>. The @fastify/type-provider-typebox plugin wires these together for fully typed handlers.
3 / 5
How does Fastify's fast-json-stringify improve response performance?
fast-json-stringify: When a route has a response schema, Fastify generates a dedicated serialiser at startup. Because the shape is known in advance, the serialiser avoids the overhead of inspecting unknown object shapes at runtime. Only properties declared in the schema are serialised — this also acts as a whitelist, preventing accidental data leaks.
4 / 5
What role does AJV play in Fastify's architecture?
AJV in Fastify: Fastify creates an AJV instance at startup and compiles each route's input schemas. The compiled validators are synchronous functions, making request validation near-zero cost at runtime. You can configure AJV options via ajv: { customOptions: { coerceTypes: true } } in Fastify's constructor to enable features like coercing query string strings to numbers.
5 / 5
How do Fastify plugins relate to schema validation?
Schema encapsulation: Fastify's plugin system uses a context tree. If you add a shared schema via fastify.addSchema() in the root context, all child plugins can reference it by $id. Schemas added inside a plugin are not visible to sibling or parent plugins. Use fastify-plugin to break encapsulation and share schemas globally.