This plugin enables you to enforce response, body and params schemas on your controllers. The sentiment behind this is that no endpoint should ever be left without validation, and now you can enforce this on your application level, so no endpoints are released without the validation.
The plugin works by "hooking" into the onRoute hook which as described in the docs, triggers when a new route is registered.
This plugin is built together with our Programmer Network Community. You can join us on Twitch and Discord.
Using npm:
npm i fastify-enforce-schema
Using yarn:
yarn add fastify-enforce-schema
Route definitions in Fastify (4.x) are synchronous, so you must ensure that this plugin is registered before your route definitions.
// ESM import Fastify from 'fastify' import enforceSchema from 'fastify-enforce-schema' const fastify = Fastify() await fastify.register(enforceSchema, { // options })Note: top-level await requires Node.js 14.8.0 or later
// CommonJS const fastify = require('fastify')() const enforceSchema = require('fastify-enforce-schema') fastify.register(enforceSchema, { // options }) fastify.register((fastify, options, done) => { // your route definitions here... done() }) // Plugins are loaded when fastify.listen(), fastify.inject() or fastify.ready() are called{ disabled: ['response', 'body', 'params'], // can also be `true` exclude: [ { url: '/foo' }, { url: '/bar', excludeSchemas: ['response'] // [..., 'body', 'params'] } ] }-
disabled: Disable specific schemas (
body,response,params) or disable the plugin by passingtrue. -
exclude: Endpoints to exclude by the
routeOptions.path. Each exclude is an object with aurland (optional)excludeSchemasarray. If theexcludeSchemasarray is not passed, validation for all 3 schemas (body,response,params) is disabled. Supports wildcards and any other RegEx features.
By default, all schemas are enforced where appropriate.
Note: The
bodyschema is only enforced on POST, PUT and PATCH routes, and theparamsschema is only enforced on routes with:params.
// Exclude all schemas fastify.get('/foo', { schema: false }, (req, reply) => { reply.code(200) }) // Exclude response and params schemas fastify.get( '/bar:baz', { schema: { response: false, params: false } }, (req, reply) => { reply.code(200) } ) // Exclude body schema fastify.post('/baz', { schema: { body: false } }, (req, reply) => { reply.code(200) })