{"id":14969182,"url":"https://github.com/fastify/ajv-compiler","last_synced_at":"2025-04-04T14:09:12.866Z","repository":{"id":37941980,"uuid":"340305839","full_name":"fastify/ajv-compiler","owner":"fastify","description":"Build and manage the AJV instances for the fastify framework","archived":false,"fork":false,"pushed_at":"2024-10-21T22:50:51.000Z","size":109,"stargazers_count":18,"open_issues_count":2,"forks_count":9,"subscribers_count":14,"default_branch":"main","last_synced_at":"2024-10-29T14:46:41.156Z","etag":null,"topics":["ajv","ajv-validation","fastify","fastify-library","json-schema"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fastify.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"fastify","open_collective":"fastify"}},"created_at":"2021-02-19T08:32:58.000Z","updated_at":"2024-10-21T22:50:49.000Z","dependencies_parsed_at":"2023-12-19T01:44:27.144Z","dependency_job_id":"5a672878-70ca-4619-bb37-1eb91b885d22","html_url":"https://github.com/fastify/ajv-compiler","commit_stats":{"total_commits":104,"total_committers":10,"mean_commits":10.4,"dds":0.5865384615384616,"last_synced_commit":"8908935527981e98dc07603aba9637789c3a5a44"},"previous_names":[],"tags_count":16,"template":false,"template_full_name":"fastify/skeleton","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Fajv-compiler","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Fajv-compiler/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Fajv-compiler/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Fajv-compiler/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fastify","download_url":"https://codeload.github.com/fastify/ajv-compiler/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247190253,"owners_count":20898702,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ajv","ajv-validation","fastify","fastify-library","json-schema"],"created_at":"2024-09-24T13:41:18.474Z","updated_at":"2025-04-04T14:09:12.847Z","avatar_url":"https://github.com/fastify.png","language":"JavaScript","readme":"# @fastify/ajv-compiler\n\n[![CI](https://github.com/fastify/ajv-compiler/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/ajv-compiler/actions/workflows/ci.yml)\n[![NPM version](https://img.shields.io/npm/v/@fastify/ajv-compiler.svg?style=flat)](https://www.npmjs.com/package/@fastify/ajv-compiler)\n[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)\n\nThis module manages the [`ajv`](https://www.npmjs.com/package/ajv) instances for the Fastify framework.\nIt isolates the `ajv` dependency so that the AJV version is not tightly coupled to the Fastify version.\nThis allows the user to decide which version of AJV to use in their Fastify-based application.\n\n\n## Versions\n\n| `@fastify/ajv-compiler` | `ajv` | Default in `fastify` |\n|------------------------:|------:|---------------------:|\n|                    v4.x |  v8.x |                 ^5.x |\n|                    v3.x |  v8.x |                 ^4.x |\n|                    v2.x |  v8.x |                    - |\n|                    v1.x |  v6.x |                ^3.14 |\n\n### AJV Configuration\n\nThe Fastify's default [`ajv` options](https://github.com/ajv-validator/ajv/tree/v6#options) are:\n\n```js\n{\n  coerceTypes: 'array',\n  useDefaults: true,\n  removeAdditional: true,\n  uriResolver: require('fast-uri'),\n  addUsedSchema: false,\n  // Explicitly set allErrors to `false`.\n  // When set to `true`, a DoS attack is possible.\n  allErrors: false\n}\n```\n\nMoreover, the [`ajv-formats`](https://www.npmjs.com/package/ajv-formats) module is included by default.\nIf you need to customize it, check the _usage_ section below.\n\nTo customize the `ajv` options, see how in the [Fastify documentation](https://fastify.dev/docs/latest/Reference/Server/#ajv).\n\n\n## Usage\n\nThis module is already used as default by Fastify.\nIf you need to provide your server instance with a different version, refer to [the Fastify docs](https://fastify.dev/docs/latest/Reference/Server/#schemacontroller).\n\n### Customize the `ajv-formats` plugin\n\nThe `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\ndoes it for you with the default configuration.\n\nIf you need to configure the `ajv-formats` plugin you can do it using the standard Fastify configuration:\n\n```js\nconst app = fastify({\n  ajv: {\n    plugins: [[require('ajv-formats'), { mode: 'fast' }]]\n  }\n})\n```\n\nIn this way, your setup will have precedence over the `@fastify/ajv-compiler` default configuration.\n\n### Customize the `ajv` instance\n\nIf you need to customize the `ajv` instance and take full control of its configuration, you can do it by\nusing the `onCreate` option in the Fastify configuration that accepts a synchronous function that receives the `ajv` instance:\n\n```js\nconst app = fastify({\n  ajv: {\n    onCreate: (ajv) =\u003e {\n      // Modify the ajv instance as you need.\n      ajv.addFormat('myFormat', (data) =\u003e typeof data === 'string')\n    }\n  }\n})\n```\n\n### Fastify with JTD\n\nThe [JSON Type Definition](https://jsontypedef.com/) feature is supported by AJV v8.x and you can benefit from it in your Fastify application.\n\nWith Fastify v3.20.x and higher, you can use the `@fastify/ajv-compiler` module to load JSON Type Definitions like so:\n\n```js\nconst factory = require('@fastify/ajv-compiler')()\n\nconst app = fastify({\n  jsonShorthand: false,\n  ajv: {\n    customOptions: { }, // additional JTD options\n    mode: 'JTD'\n  },\n  schemaController: {\n    compilersFactory: {\n      buildValidator: factory\n    }\n  }\n})\n```\n\nThe default AJV JTD options are the same as [Fastify's default options](#AJV-Configuration).\n\n#### Fastify with JTD and serialization\n\nYou can use JTD Schemas to serialize your response object too:\n\n```js\nconst factoryValidator = require('@fastify/ajv-compiler')()\nconst factorySerializer = require('@fastify/ajv-compiler')({ jtdSerializer: true })\n\nconst app = fastify({\n  jsonShorthand: false,\n  ajv: {\n    customOptions: { }, // additional JTD options\n    mode: 'JTD'\n  },\n  schemaController: {\n    compilersFactory: {\n      buildValidator: factoryValidator,\n      buildSerializer: factorySerializer\n    }\n  }\n})\n```\n\n\n### AJV Standalone\n\nAJV v8 introduced a [standalone feature](https://ajv.js.org/standalone.html) that lets you pre-compile your schemas and use them in your application for a faster startup.\n\nTo use this feature, you must be aware of the following:\n\n1. You must generate and save the application's compiled schemas.\n2. Read the compiled schemas from the file and provide them back to your Fastify application.\n\n\n#### Generate and save the compiled schemas\n\nFastify helps you to generate the validation schemas functions and it is your choice to save them where you want.\nTo accomplish this, you must use a new compiler: `StandaloneValidator`.\n\nYou must provide 2 parameters to this compiler:\n\n- `readMode: false`: a boolean to indicate that you want to generate the schemas functions string.\n- `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.\n\nWhen `readMode: false`, **the compiler is meant to be used in development ONLY**.\n\n\n```js\nconst { StandaloneValidator } = require('@fastify/ajv-compiler')\nconst factory = StandaloneValidator({\n  readMode: false,\n  storeFunction (routeOpts, schemaValidationCode) {\n    // routeOpts is like: { schema, method, url, httpPart }\n    // schemaValidationCode is a string source code that is the compiled schema function\n    const fileName = generateFileName(routeOpts)\n    fs.writeFileSync(path.join(__dirname, fileName), schemaValidationCode)\n  }\n})\n\nconst app = fastify({\n  jsonShorthand: false,\n  schemaController: {\n    compilersFactory: {\n      buildValidator: factory\n    }\n  }\n})\n\n// ... add all your routes with schemas ...\n\napp.ready().then(() =\u003e {\n  // at this stage all your schemas are compiled and stored in the file system\n  // now it is important to turn off the readMode\n})\n```\n\n#### Read the compiled schemas functions\n\nAt this stage, you should have a file for every route's schema.\nTo use them, you must use the `StandaloneValidator` with the parameters:\n\n- `readMode: true`: a boolean to indicate that you want to read and use the schemas functions string.\n- `restoreFunction`\" a sync function that must return a function to validate the route.\n\nImportant keep away before you continue reading the documentation:\n\n- when you use the `readMode: true`, the application schemas are not compiled (they are ignored). So, if you change your schemas, you must recompile them!\n- as you can see, you must relate the route's schema to the file name using the `routeOpts` object. You may use the `routeOpts.schema.$id` field to do so, it is up to you to define a unique schema identifier.\n\n```js\nconst { StandaloneValidator } = require('@fastify/ajv-compiler')\nconst factory = StandaloneValidator({\n  readMode: true,\n  restoreFunction (routeOpts) {\n    // routeOpts is like: { schema, method, url, httpPart }\n    const fileName = generateFileName(routeOpts)\n    return require(path.join(__dirname, fileName))\n  }\n})\n\nconst app = fastify({\n  jsonShorthand: false,\n  schemaController: {\n    compilersFactory: {\n      buildValidator: factory\n    }\n  }\n})\n\n// ... add all your routes with schemas as before...\n\napp.listen({ port: 3000 })\n```\n\n### How it works\n\nThis module provides a factory function to produce [Validator Compilers](https://fastify.dev/docs/latest/Reference/Server/#validatorcompiler) functions.\n\nThe 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.\n\nEvery 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.\n\nThe variables involved to choose if a Validator Compiler can be reused are:\n\n- the AJV configuration: it is [one per server](https://fastify.dev/docs/latest/Reference/Server/#ajv)\n- the external JSON schemas: once a new schema is added to a fastify's context, calling `fastify.addSchema()`, it will cause a new AJV initialization\n\n\n## License\n\nLicensed under [MIT](./LICENSE).\n","funding_links":["https://github.com/sponsors/fastify","https://opencollective.com/fastify"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Fajv-compiler","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffastify%2Fajv-compiler","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Fajv-compiler/lists"}