The Validation Engine Under the Hood
Tuning Ajv
Fastify validates with Ajv 8. You can tune compile options, add format support, and customize error messages.
What you'll learn
- Enable additional formats with ajv-formats
- Toggle coerceTypes and useDefaults
- Wire custom error messages with ajv-errors
Ajv compiles each JSON Schema into a specialized JavaScript validator the first time it sees the schema, then reuses that validator forever. Fastify exposes Ajv’s options through the factory.
Common Options
import Fastify from 'fastify';
import ajvFormats from 'ajv-formats';
import ajvErrors from 'ajv-errors';
const app = Fastify({
ajv: {
customOptions: {
removeAdditional: 'all',
coerceTypes: 'array',
useDefaults: true,
allErrors: true,
},
plugins: [ajvFormats, ajvErrors],
},
}); removeAdditional— strips unknown body keys instead of throwingcoerceTypes— turns string'42'into number42for query/paramsuseDefaults— fills indefaultvalues you declared in the schemaallErrors— collects every problem in one response, not just the first
Add Formats
ajv-formats registers email, uri, uuid, date, date-time, ipv4, regex, and more.
Without it, those format keywords are ignored silently.
Custom Error Messages
ajv-errors lets you attach human-friendly messages right inside the schema:
const schema = {
type: 'object',
required: ['email'],
properties: {
email: { type: 'string', format: 'email' },
},
errorMessage: {
required: { email: 'We need your email to sign you up.' },
properties: { email: 'That does not look like a valid email.' },
},
} as const; Fastify forwards every validation failure to the error handler — see the next lesson for shaping the response.
Error Responses →