You can use the Ajv library directly, however for an Express based API it's nice to be able to use middleware to validate request data which has been sent to an endpoint before that endpoint's route handler is run. This allows you to prevent things like accidentally storing invalid data in your database. It also means that you can handle validation errors and send a useful error response back to the client. The express-json-validator-middleware package can help you with all of this.
The express-json-validator-middleware package uses Ajv and allows you to pass configuration options to it. This is great as it means you have full control to configure Ajv as if you were using it directly.
Before we integrate this middleware into our application, let's get it installed:
npm install express-json-validator-middleware
Once you have it installed you need to require it in your application and configure it:
// src/middleware/json-validator.js import { Validator } from "express-json-validator-middleware"; /** * Create a new instance of the `express-json-validator-middleware` * `Validator` class and pass in Ajv options if needed. * * @see https://github.com/ajv-validator/ajv/blob/master/docs/api.md#options */ const validator = new Validator(); export default validator.validate;
(Example 2.6)