Compile Validation and Serialization with Fastify JSON Schema
Fastify compiles JSON Schema at startup so invalid requests never reach your handler and responses stay consistent.
21 Sept 2025, 10:22 UTC

The problem: validation scattered across route handlers
Many Node.js APIs validate request bodies with inline if statements or ad-hoc middleware. One route checks for a missing name field; another trusts the caller and sanitizes later. Responses are equally inconsistent: some endpoints return raw database rows, others hand-rolled JSON shapes. The result is slow development, hard-to-debug production incidents, and runtime overhead from checks repeated on every request.
Fastify compiles JSON Schema once, at startup
Fastify treats JSON Schema as a first-class routing concern. When you attach a schema to a route, Fastify compiles it during server boot using Ajv for request validation and fast-json-stringify for response serialization. Instead of interpreting conditions at runtime, the framework executes pre-compiled functions. Invalid requests are rejected automatically, typically with a 400 status, before reaching your handler. Response objects are serialized according to the schema, which can also strip fields you did not intend to expose.
This behavior is version-sensitive. Fastify major versions ship with different Ajv defaults and schema options. Check the installed Fastify and Ajv versions in package.json and compare against the official schema guide for that major version before relying on coercion, custom keywords, or strict mode.
What the schema controls
body: shape and types of the incoming request payload.params: validation for URL parameters.querystring: validation for query parameters.response: serialization rules for outgoing JSON, including which properties to include.
Worked example: a validated items route
Create a file named app.js in your project directory:
const fastify = require('fastify')({ logger: true })
fastify.post('/items', {
schema: {
body: {
type: 'object',
required: ['name', 'quantity'],
properties: {
name: { type: 'string', minLength: 1 },
quantity: { type: 'integer', minimum: 0 }
},
additionalProperties: false
},
response: {
201: {
type: 'object',
properties: {
id: { type: 'string' },
name: { type: 'string' },
quantity: { type: 'integer' }
}
}
}
}
}, async (request, reply) => {
const item = { id: 'item-' + Date.now(), ...request.body }
return reply.code(201).send(item)
})
fastify.listen({ port: 3000 }, (err) => {
if (err) throw err
})
Run this from your terminal in the project directory. No special permissions are required unless you choose a port below 1024, which needs elevated privileges.
Check behavior with curl
Send a valid payload:
curl -X POST http://localhost:3000/items \
-H 'Content-Type: application/json' \
-d '{"name":"widget","quantity":5}'
Expected check: a 201 response containing only id, name, and quantity. Extra fields in the request body should be stripped by additionalProperties: false; extra fields in the handler return value should be stripped by the response schema.
Send an invalid payload:
curl -X POST http://localhost:3000/items \
-H 'Content-Type: application/json' \
-d '{"name":"","quantity":-1}'
Expected check: Fastify should reject the request before the handler runs, typically with a 400 status and a validation error message. If you see a 201 instead, your schema may be too permissive or your Fastify/Ajv version may handle coercion differently than expected.
Risk: setting additionalProperties: true or omitting required lets malformed data reach your handler, which removes the safety benefit of compiled validation.
Trade-offs and limitations
- Startup cost. Compiling many large or complex schemas increases boot time. Measure your specific workload before assuming the trade-off is worth it.
- JSON only by default. Response serialization applies to JSON content types. Plain text, HTML, or stream responses bypass
fast-json-stringifyand need custom serializers if you want the same guarantees. - Maintenance overhead. Large JSON Schema files are verbose. A team must decide whether schema definitions live inline with routes or in shared modules.
- Version drift. Ajv behavior changes between versions. Pin dependencies and test schema behavior after upgrades.
Practical verification
- Open
package.jsonand note the Fastify and Ajv versions. - Start the minimal app above and send one valid and one invalid request with curl.
- Confirm invalid requests return 400 and valid responses contain only serialized properties.
- If you need performance data, benchmark startup time and throughput with and without schemas using a tool such as autocannon in a staging environment, not production.
There is no rollback step because adding a route schema changes application code, not live infrastructure. To revert, remove the schema object and redeploy the previous version of the file.
Closing
Fastify's JSON Schema support moves validation and serialization out of your request path and into startup compilation. It is not free: boot time rises and schema maintenance becomes a real concern. For APIs where request shape and response consistency matter, the trade-off usually pays off. Start with one route, verify the 400 behavior, and expand only after confirming your Fastify and Ajv versions behave as expected.