Validating the Payload of HTTP Requests in Express.js
Express.js·3 min read·Jan 1, 2025
The second and probably most important part of the data handling process after parsing is called validation, as parsing alone is not enough to guarantee that the data sent by a user or another application respects the API contract.
In this context, validation refers to the process of ensuring the accuracy of the parsed data by matching its value, type, and format against a predefined model.
Getting started with Joi
Joi is a JavaScript library used for validating objects.
$ npm install --save joiThe validation of an object with Joi is a two step process:
-
First, we need to construct the schema of this object using types and constraints.
-
Second, we need to validate this schema against an arbitrary value, which in this case will be the parsed message body of an incoming request.
Creating a validation schema
In Joi, a schema refers to a set of rules that define the structure, types, and constraints that an object must adhere to in order to be considered valid.
To create a schema, we can use the top-level object() method exported by the joi module that takes as argument an object:
const Joi = require('joi');Unlock the Build RESTful APIs in Node.js module
Learn how to build real database-backed and framework-powered RESTful APIs with MySQL, Sequelize, and Express.
You get immediate access to:
- 37 focused lessons across MySQL, Sequelize, backend, and Express
- 4 real-world projects with commented solutions
- Ongoing updates to this bundle
- Lifetime access to this bundle