Gathering detailed insights and metrics for @fastify/ajv-compiler
Gathering detailed insights and metrics for @fastify/ajv-compiler
Gathering detailed insights and metrics for @fastify/ajv-compiler
Gathering detailed insights and metrics for @fastify/ajv-compiler
@firanorg/mollitia-molestias-accusamus
[![github actions][actions-image]][actions-url] [![coverage][codecov-image]][codecov-url] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url]
@teamteanpm2024/nam-facilis-laudantium
security holding package
@npmtuanmap/ex-vel-expedita-impedit
@crabas0npm2/impedit-porro-maiores
security holding package
Build and manage the AJV instances for the fastify framework
npm install @fastify/ajv-compiler
Typescript
Module System
Node Version
NPM Version
JavaScript (86.22%)
TypeScript (13.78%)
Total Downloads
210,516,087
Last Day
111,581
Last Week
2,164,522
Last Month
9,445,764
Last Year
97,366,747
NOASSERTION License
21 Stars
126 Commits
11 Forks
12 Watchers
2 Branches
23 Contributors
Updated on Jun 23, 2025
Minified
Minified + Gzipped
Latest Version
4.0.2
Package Id
@fastify/ajv-compiler@4.0.2
Unpacked Size
52.71 kB
Size
13.26 kB
File Count
24
NPM Version
10.8.2
Node Version
20.18.1
Published on
Jan 03, 2025
Cumulative downloads
Total Downloads
Last Day
-2.6%
111,581
Compared to previous day
Last Week
-8.2%
2,164,522
Compared to previous week
Last Month
0.4%
9,445,764
Compared to previous month
Last Year
47.1%
97,366,747
Compared to previous year
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:
1{ 2 coerceTypes: 'array', 3 useDefaults: true, 4 removeAdditional: true, 5 uriResolver: require('fast-uri'), 6 addUsedSchema: false, 7 // Explicitly set allErrors to `false`. 8 // When set to `true`, a DoS attack is possible. 9 allErrors: false 10}
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:
1const app = fastify({ 2 ajv: { 3 plugins: [[require('ajv-formats'), { mode: 'fast' }]] 4 } 5})
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:
1const app = fastify({ 2 ajv: { 3 onCreate: (ajv) => { 4 // Modify the ajv instance as you need. 5 ajv.addFormat('myFormat', (data) => typeof data === 'string') 6 } 7 } 8})
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:
1const factory = require('@fastify/ajv-compiler')() 2 3const app = fastify({ 4 jsonShorthand: false, 5 ajv: { 6 customOptions: { }, // additional JTD options 7 mode: 'JTD' 8 }, 9 schemaController: { 10 compilersFactory: { 11 buildValidator: factory 12 } 13 } 14})
The default AJV JTD options are the same as Fastify's default options.
You can use JTD Schemas to serialize your response object too:
1const factoryValidator = require('@fastify/ajv-compiler')() 2const factorySerializer = require('@fastify/ajv-compiler')({ jtdSerializer: true }) 3 4const app = fastify({ 5 jsonShorthand: false, 6 ajv: { 7 customOptions: { }, // additional JTD options 8 mode: 'JTD' 9 }, 10 schemaController: { 11 compilersFactory: { 12 buildValidator: factoryValidator, 13 buildSerializer: factorySerializer 14 } 15 } 16})
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.
1const { StandaloneValidator } = require('@fastify/ajv-compiler')
2const factory = StandaloneValidator({
3 readMode: false,
4 storeFunction (routeOpts, schemaValidationCode) {
5 // routeOpts is like: { schema, method, url, httpPart }
6 // schemaValidationCode is a string source code that is the compiled schema function
7 const fileName = generateFileName(routeOpts)
8 fs.writeFileSync(path.join(__dirname, fileName), schemaValidationCode)
9 }
10})
11
12const app = fastify({
13 jsonShorthand: false,
14 schemaController: {
15 compilersFactory: {
16 buildValidator: factory
17 }
18 }
19})
20
21// ... add all your routes with schemas ...
22
23app.ready().then(() => {
24 // at this stage all your schemas are compiled and stored in the file system
25 // now it is important to turn off the readMode
26})
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.1const { StandaloneValidator } = require('@fastify/ajv-compiler') 2const factory = StandaloneValidator({ 3 readMode: true, 4 restoreFunction (routeOpts) { 5 // routeOpts is like: { schema, method, url, httpPart } 6 const fileName = generateFileName(routeOpts) 7 return require(path.join(__dirname, fileName)) 8 } 9}) 10 11const app = fastify({ 12 jsonShorthand: false, 13 schemaController: { 14 compilersFactory: { 15 buildValidator: factory 16 } 17 } 18}) 19 20// ... add all your routes with schemas as before... 21 22app.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.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
GitHub workflow tokens follow principle of least privilege
Details
Reason
0 existing vulnerabilities detected
Reason
security policy file detected
Details
Reason
license file detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 9
Details
Reason
3 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 2
Reason
Found 5/23 approved changesets -- score normalized to 2
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Score
Last Scanned on 2025-06-30
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More