JSON Schema integration for request validation, response serialization, and documentation generation.
Add and retrieve shared schemas for reuse across routes.
/**
* Add a schema to the shared schema store
* @param schema - JSON schema object with $id property
* @returns FastifyInstance for method chaining
*/
addSchema(schema: object): FastifyInstance;
/**
* Retrieve a schema from the shared store by ID
* @param schemaId - Schema identifier
* @returns Schema object or undefined
*/
getSchema(schemaId: string): unknown;
/**
* Get all schemas from the shared store
* @returns Object mapping schema IDs to schema objects
*/
getSchemas(): Record<string, unknown>;Usage Examples:
// Add reusable schemas
fastify.addSchema({
$id: 'user',
type: 'object',
properties: {
id: { type: 'string' },
name: { type: 'string' },
email: { type: 'string', format: 'email' }
},
required: ['id', 'name', 'email']
});
// Use schema in routes
fastify.post('/users', {
schema: {
body: { $ref: 'user#' },
response: {
201: { $ref: 'user#' }
}
}
}, handler);
// Retrieve schemas
const userSchema = fastify.getSchema('user');
const allSchemas = fastify.getSchemas();Configure custom schema validation compilation.
/**
* Set custom validator compiler for JSON schemas
* @param compiler - Function that compiles schemas to validators
* @returns FastifyInstance for method chaining
*/
setValidatorCompiler(compiler: FastifySchemaCompiler): FastifyInstance;
/**
* Schema compiler function signature
*/
type FastifySchemaCompiler = (
routeSchema: FastifySchema
) => (data: any) => boolean | any;Usage Examples:
const Ajv = require('ajv');
const addFormats = require('ajv-formats');
// Custom AJV configuration
const ajv = new Ajv({
allErrors: true,
removeAdditional: true,
useDefaults: true,
coerceTypes: true
});
addFormats(ajv);
// Set custom validator compiler
fastify.setValidatorCompiler(({ schema }) => {
return ajv.compile(schema);
});Configure response serialization for optimal performance.
/**
* Set custom serializer compiler for responses
* @param compiler - Function that compiles schemas to serializers
* @returns FastifyInstance for method chaining
*/
setSerializerCompiler(compiler: FastifySerializerCompiler): FastifyInstance;
/**
* Serializer compiler function signature
*/
type FastifySerializerCompiler = (
routeSchema: FastifySchema
) => (data: any) => string;
/**
* Set default reply serializer
* @param serializer - Default serialization function
* @returns FastifyInstance for method chaining
*/
setReplySerializer(serializer: (payload: any) => string): FastifyInstance;Usage Examples:
const FastJsonStringify = require('fast-json-stringify');
// Custom serializer compiler
fastify.setSerializerCompiler(({ schema }) => {
return FastJsonStringify(schema);
});
// Default reply serializer
fastify.setReplySerializer((payload) => {
return JSON.stringify(payload, null, 2);
});Advanced schema management with custom buckets and compilers.
/**
* Configure schema controller options
* @param options - Schema controller configuration
* @returns FastifyInstance for method chaining
*/
setSchemaController(options: FastifySchemaControllerOptions): FastifyInstance;
interface FastifySchemaControllerOptions {
bucket?: (parentSchemas?: unknown) => {
add(schema: unknown): FastifyInstance;
getSchema(schemaId: string): unknown;
getSchemas(): Record<string, unknown>;
};
compilersFactory?: {
buildValidator?: ValidatorFactory;
buildSerializer?: SerializerFactory;
};
}Customize schema validation error messages.
/**
* Set custom schema error formatter
* @param formatter - Function to format validation errors
* @returns FastifyInstance for method chaining
*/
setSchemaErrorFormatter(formatter: SchemaErrorFormatter): FastifyInstance;
/**
* Schema error formatter function signature
*/
type SchemaErrorFormatter = (
errors: FastifySchemaValidationError[],
dataVar: string
) => Error;
interface FastifySchemaValidationError {
instancePath: string;
schemaPath: string;
keyword: string;
params: object;
message?: string;
data?: any;
}Usage Examples:
// Custom error formatter
fastify.setSchemaErrorFormatter((errors, dataVar) => {
const error = new Error('Validation failed');
error.statusCode = 400;
error.validation = errors.map(err => ({
field: err.instancePath.replace('/', '') || dataVar,
message: err.message,
value: err.data
}));
return error;
});Complete schema definition for routes.
interface FastifySchema {
body?: object; // Request body schema
querystring?: object; // Query parameters schema
params?: object; // URL parameters schema
headers?: object; // Request headers schema
response?: { // Response schemas by status code
[statusCode: string]: object;
};
security?: object[]; // OpenAPI security requirements
tags?: string[]; // OpenAPI tags
description?: string; // Route description
summary?: string; // Route summary
consumes?: string[]; // Content types accepted
produces?: string[]; // Content types produced
deprecated?: boolean; // Mark route as deprecated
}Usage Examples:
// Complete route schema
fastify.post('/users', {
schema: {
description: 'Create a new user',
tags: ['users'],
summary: 'User creation endpoint',
body: {
type: 'object',
properties: {
name: { type: 'string', minLength: 1 },
email: { type: 'string', format: 'email' },
age: { type: 'integer', minimum: 0, maximum: 150 }
},
required: ['name', 'email'],
additionalProperties: false
},
querystring: {
type: 'object',
properties: {
notify: { type: 'boolean', default: true }
}
},
headers: {
type: 'object',
properties: {
'x-api-key': { type: 'string' }
},
required: ['x-api-key']
},
response: {
201: {
type: 'object',
properties: {
id: { type: 'string' },
name: { type: 'string' },
email: { type: 'string' },
createdAt: { type: 'string', format: 'date-time' }
}
},
400: {
type: 'object',
properties: {
error: { type: 'string' },
message: { type: 'string' }
}
}
}
}
}, async (request, reply) => {
const user = await createUser(request.body);
reply.code(201).send(user);
});Control validation behavior per route.
// Attach validation results to request
fastify.post('/users', {
attachValidation: true,
schema: {
body: userSchema
}
}, async (request, reply) => {
if (request.validationError) {
// Handle validation error manually
reply.code(400).send({
error: 'Validation failed',
details: request.validationError.validation
});
return;
}
// Process valid request
const user = await createUser(request.body);
reply.send(user);
});Transform and coerce data types during validation.
// Schema with type coercion
const coercionSchema = {
type: 'object',
properties: {
age: { type: 'integer' }, // "25" -> 25
active: { type: 'boolean' }, // "true" -> true
tags: { // "tag1,tag2" -> ["tag1", "tag2"]
type: 'array',
items: { type: 'string' },
transform: ['trim', 'toLowerCase']
},
metadata: {
type: 'object',
default: {} // Add default empty object
}
}
};
// Remove additional properties
const strictSchema = {
type: 'object',
properties: {
name: { type: 'string' },
email: { type: 'string' }
},
additionalProperties: false // Remove extra properties
};