Lesson 10 / 32
JSON Schema & Validation
Validate request bodies, queries and params with JSON Schema, and reject invalid input automatically.
Schema-driven validation
Fastify uses JSON Schema to validate request bodies, query strings, and URL parameters. Invalid requests are rejected with 400 Bad Request automatically.
Defining a schema
Pass a schema object in route options. It can validate body, querystring, params, and response.
const createItemSchema = {
body: {
type: 'object',
required: ['name', 'price'],
properties: {
name: { type: 'string' },
price: { type: 'number', minimum: 0 },
},
},
};
fastify.post('/items', { schema: createItemSchema }, async (req) => {
// req.body is guaranteed to have name and price
return { id: 1, ...req.body };
});Query and params schemas
Validate URL parameters and query strings the same way.
const listSchema = {
querystring: {
type: 'object',
properties: {
page: { type: 'integer', minimum: 1 },
limit: { type: 'integer', minimum: 1, maximum: 100 },
},
},
params: {
type: 'object',
required: ['userId'],
properties: {
userId: { type: 'string' },
},
},
};
fastify.get('/users/:userId/items', { schema: listSchema }, async (req) => {
return [];
});Validating a body with schema
Fastify compiles the schema with Ajv at startup.
requiredrejects missing fields.- Invalid input gets
400before your handler runs.
const fastify = require('fastify')();
fastify.post('/user', {
schema: {
body: {
type: 'object',
required: ['name'],
properties: { name: { type: 'string', minLength: 2 } }
}
}
}, async (req) => ({ hello: req.body.name }));
fastify.listen({ port: 3000 });Quick check
Quick check: Why does a response schema make Fastify faster?
- It caches the database
- It compiles a specialised serializer instead of generic JSON.stringify
- It disables logging
Answer
It compiles a specialised serializer instead of generic JSON.stringify — fast-json-stringify generates serialization code from the schema, and it also drops undeclared fields.