
Security News
GitHub Actions Pricing Whiplash: Self-Hosted Actions Billing Change Postponed
GitHub postponed a new billing model for self-hosted Actions after developer pushback, but moved forward with hosted runner price cuts on January 1.
@fastify/ajv-compiler
Advanced tools
This module manages the ajv instances for the Fastify framework.
It isolates the ajv dependency so that the AJV version is not tightly coupled to the Fastify version.
This allows the user to decide which version of AJV to use in their Fastify-based application.
@fastify/ajv-compiler | ajv | Default in fastify |
|---|---|---|
| v4.x | v8.x | ^5.x |
| v3.x | v8.x | ^4.x |
| v2.x | v8.x | - |
| v1.x | v6.x | ^3.14 |
The Fastify's default ajv options are:
{
coerceTypes: 'array',
useDefaults: true,
removeAdditional: true,
uriResolver: require('fast-uri'),
addUsedSchema: false,
// Explicitly set allErrors to `false`.
// When set to `true`, a DoS attack is possible.
allErrors: false
}
Moreover, the ajv-formats module is included by default.
If you need to customize it, check the usage section below.
To customize the ajv options, see how in the Fastify documentation.
This module is already used as default by Fastify. If you need to provide your server instance with a different version, refer to the Fastify docs.
ajv-formats pluginThe format keyword is not part of the official ajv module since v7. To use it, you need to install the ajv-formats module and this module
does it for you with the default configuration.
If you need to configure the ajv-formats plugin you can do it using the standard Fastify configuration:
const app = fastify({
ajv: {
plugins: [[require('ajv-formats'), { mode: 'fast' }]]
}
})
In this way, your setup will have precedence over the @fastify/ajv-compiler default configuration.
ajv instanceIf you need to customize the ajv instance and take full control of its configuration, you can do it by
using the onCreate option in the Fastify configuration that accepts a synchronous function that receives the ajv instance:
const app = fastify({
ajv: {
onCreate: (ajv) => {
// Modify the ajv instance as you need.
ajv.addFormat('myFormat', (data) => typeof data === 'string')
}
}
})
The JSON Type Definition feature is supported by AJV v8.x and you can benefit from it in your Fastify application.
With Fastify v3.20.x and higher, you can use the @fastify/ajv-compiler module to load JSON Type Definitions like so:
const factory = require('@fastify/ajv-compiler')()
const app = fastify({
jsonShorthand: false,
ajv: {
customOptions: { }, // additional JTD options
mode: 'JTD'
},
schemaController: {
compilersFactory: {
buildValidator: factory
}
}
})
The default AJV JTD options are the same as Fastify's default options.
You can use JTD Schemas to serialize your response object too:
const factoryValidator = require('@fastify/ajv-compiler')()
const factorySerializer = require('@fastify/ajv-compiler')({ jtdSerializer: true })
const app = fastify({
jsonShorthand: false,
ajv: {
customOptions: { }, // additional JTD options
mode: 'JTD'
},
schemaController: {
compilersFactory: {
buildValidator: factoryValidator,
buildSerializer: factorySerializer
}
}
})
AJV v8 introduced a standalone feature that lets you pre-compile your schemas and use them in your application for a faster startup.
To use this feature, you must be aware of the following:
Fastify helps you to generate the validation schemas functions and it is your choice to save them where you want.
To accomplish this, you must use a new compiler: StandaloneValidator.
You must provide 2 parameters to this compiler:
readMode: false: a boolean to indicate that you want to generate the schemas functions string.storeFunction" a sync function that must store the source code of the schemas functions. You may provide an async function too, but you must manage errors.When readMode: false, the compiler is meant to be used in development ONLY.
const { StandaloneValidator } = require('@fastify/ajv-compiler')
const factory = StandaloneValidator({
readMode: false,
storeFunction (routeOpts, schemaValidationCode) {
// routeOpts is like: { schema, method, url, httpPart }
// schemaValidationCode is a string source code that is the compiled schema function
const fileName = generateFileName(routeOpts)
fs.writeFileSync(path.join(__dirname, fileName), schemaValidationCode)
}
})
const app = fastify({
jsonShorthand: false,
schemaController: {
compilersFactory: {
buildValidator: factory
}
}
})
// ... add all your routes with schemas ...
app.ready().then(() => {
// at this stage all your schemas are compiled and stored in the file system
// now it is important to turn off the readMode
})
At this stage, you should have a file for every route's schema.
To use them, you must use the StandaloneValidator with the parameters:
readMode: true: a boolean to indicate that you want to read and use the schemas functions string.restoreFunction" a sync function that must return a function to validate the route.Important keep away before you continue reading the documentation:
readMode: true, the application schemas are not compiled (they are ignored). So, if you change your schemas, you must recompile them!routeOpts object. You may use the routeOpts.schema.$id field to do so, it is up to you to define a unique schema identifier.const { StandaloneValidator } = require('@fastify/ajv-compiler')
const factory = StandaloneValidator({
readMode: true,
restoreFunction (routeOpts) {
// routeOpts is like: { schema, method, url, httpPart }
const fileName = generateFileName(routeOpts)
return require(path.join(__dirname, fileName))
}
})
const app = fastify({
jsonShorthand: false,
schemaController: {
compilersFactory: {
buildValidator: factory
}
}
})
// ... add all your routes with schemas as before...
app.listen({ port: 3000 })
This module provides a factory function to produce Validator Compilers functions.
The Fastify factory function is just one per server instance and it is called for every encapsulated context created by the application through the fastify.register() call.
Every Validator Compiler produced has a dedicated AJV instance, so this factory will try to produce as less as possible AJV instances to reduce the memory footprint and the startup time.
The variables involved to choose if a Validator Compiler can be reused are:
fastify.addSchema(), it will cause a new AJV initializationLicensed under MIT.
AJV (Another JSON Schema Validator) is a standalone JSON schema validator that can be used in various JavaScript environments. It is highly performant and supports JSON Schema draft-07 and later. Compared to @fastify/ajv-compiler, AJV is a more general-purpose library that can be used outside of the Fastify framework.
Joi is a powerful schema description language and data validator for JavaScript. It allows you to create blueprints for JavaScript objects to ensure validation. While Joi is not specifically designed for Fastify, it can be integrated with Fastify using plugins. Compared to @fastify/ajv-compiler, Joi offers a different approach to schema validation with a focus on object schema descriptions.
Yup is a JavaScript schema builder for value parsing and validation. It is similar to Joi but focuses on a more functional programming style. Yup can be used in various environments, including client-side and server-side applications. Compared to @fastify/ajv-compiler, Yup provides a more flexible and chainable API for schema validation.
FAQs
Build and manage the AJV instances for the fastify framework
The npm package @fastify/ajv-compiler receives a total of 1,306,474 weekly downloads. As such, @fastify/ajv-compiler popularity was classified as popular.
We found that @fastify/ajv-compiler demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 11 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
GitHub postponed a new billing model for self-hosted Actions after developer pushback, but moved forward with hosted runner price cuts on January 1.

Research
Destructive malware is rising across open source registries, using delays and kill switches to wipe code, break builds, and disrupt CI/CD.

Security News
Socket CTO Ahmad Nassri shares practical AI coding techniques, tools, and team workflows, plus what still feels noisy and why shipping remains human-led.