Schema Validation in Node.js With Joi (2024)

Accepting untested and unvalidated data into a web application can cause security vulnerabilities, and unforeseen issues can arise from the invalid data.

Node.js ORMs, such as Sequelize and TypeORM, allow you to set validation rules out of the box at the application level. During API development, data comes from HTTP requests to specific endpoints. This happens at the request level; thus, the default validation offered by the ORMs doesn't apply to them.

Joi is a schema description and data validator for JavaScript. Here, you will learn how to use the Joi validation library to validate data at the request level.

Setting Up Demo Project

To demonstrate how Joi validates data, you will build a simple demo application that mimics an actual application.

Schema Validation in Node.js With Joi (1)

First, create a project folder and move into it by running the following command:

mkdir demoapp && cd demoapp

Next, initialize npm in your project directory by running:

npm init -y

Next, you will need to install some dependencies. The dependencies required for this tutorial include the following:

  • Express: Express is a Node.js framework that provides a robust set of features for web and mobile applications. Express makes it easier to build backend applications with Node.js.
  • Joi: Joi is a data validation library for Node.js.

Install the dependencies with the node package manager by running the command below:

npm install express joi

Next, create an index.js file in your root directory and add the following code block to it:

const express = require("express");
const router = require("./routes");
const port = 3000;

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(router);

app.listen(port, () => {
console.log("app listening on port 3000!");
});

The code block above sets up a simple Express server. It configures middleware to parse incoming request data and handle incoming requests and starts the server to listen for incoming requests on port 3000.

Routing and Handling Requests

For simplicity, you will create a request handler middleware that returns a status code, along with the request body, as a response to every request that attempts to send data to your application.

Create a handler.js file in your project’s root directory and add the code block below:

const demoHandler = (req, res, next) => {
res.send({
code: 201,
data: req.body,
});
next();
};

module.exports = demoHandler;

Next, create a router.js file in your project’s root directory and add the code block below to your file:

const express = require("express");
const demoHandler = require("./handler");
const router = express.Router();

router.post("/signup", demoHandler);

module.exports = router;

Creating a Joi Schema

A Joi schema represents a specific data object's expected structure and validation rules.

To create a Joi schema, you can use the Joi.object() method and chain various validation rules exposed by Joi to define the structure and validation requirements for your data.

For example:

const exampleSchema = Joi.object({
name: Joi.string().min(3).required(),
});

The example above describes a simple Joi schema with a name property. The name property has a value of Joi.string().min(3).required(). This means that the name value should be a string, with a minimum length of 3 characters, and it is required.

Using Joi, you can chain various methods to add more validation constraints to each field defined in your schema.

Here’s an example with more fields and validation constraints:

const userSchema = Joi.object({
email: Joi.string().email().required(),

password: Joi.string().min(6).required(),

age: Joi.number().min(18).optional(),

employed: Joi.boolean().optional(),

phone: Joi.string()
.regex(/^\\d{3}-\\d{3}-\\d{4}$/)//"123-456-7890"
.required(),

address: Joi.object({
street: Joi.string().min(3).required(),
city: Joi.string().min(3).required(),
state: Joi.string().min(3).required(),
zip: Joi.number().min(3).required(),
}).required(),

hobbies: Joi.array().items(Joi.string()).required(),

}).options({ abortEarly: false });

The userSchema defines the following constraints for each property:

  • email: Must be a valid email string.
  • password: Must be a string with a minimum of 6 characters.
  • age: An optional number with a minimum value of 18.
  • employed: An optional boolean.
  • phone: A required string that matches the specified regex expression (/^\d{3}-\d{3}-\d{4}$/).
  • address: An object representing the user's address with the following sub-properties.
    • street: A required string with a minimum length of 3 characters.
    • city: A required string with a minimum length of 3 characters.
    • state: A required string with a minimum length of 3 characters.
    • zip: A required number with a minimum value of 3.
  • hobbies: A required array of strings.

In addition to the constraints, userSchema sets the abortEarly option to false. By default, Joi stops the execution of the program as soon as it encounters the first error and prints the error to the console. However, setting this option to false ensures that Joi checks the entire schema and prints all the encountered errors to the console.

Validating Data With Joi

Create a validation.js file and add the userSchema code to it.

Like so:

//validation.js
const Joi = require("joi");

const userSchema = Joi.object({
//...
}).options({ abortEarly: false });

module.exports = userSchema;

Then, create a middleware that intercepts request payloads and verifies them against a provided schema by adding the following code below the userSchema code.

const validationMiddleware = (schema) => {
return(req, res, next) => {
const { error } = schema.validate(req.body);

if (error) {
// Handle validation error
console.log(error.message);

res.status(400).json({ errors: error.details });
} else {
// Data is valid, proceed to the next middleware
next();
}
};
};

When a request is made, the middleware invokes the validate method of the schema to validate the request body. If any validation errors occur, the middleware sends a 400 Bad Request response with the error messages extracted from the validation error details.

On the other hand, if the validation passes without errors, the middleware calls the next() function.

Finally, export the validationMiddleware and userSchema.

module.exports = {
userSchema,
validationMiddleware,
};

Testing Validation Constraints

Import validationMiddleware and userSchema into your router.js file and set up the middleware like so:

const { validationMiddleware, userSchema } = require("./validation");

router.post("/signup", validationMiddleware(userSchema), demoHandler);

Start your application by running the command below:

nodeindex.js

Then, make an HTTP POST request to localhost:3000/signup using the test data below. You can achieve this using cURL or any other API client.

{
"email": "user@example", // Invalid email format
"password": "pass", // Password length less than 6 characters
"age": 15, // Age below 18
"employed": true,
"hobbies": ["reading", "running"],
"phone": "123-456-789", // Invalid phone number format
"address": {
"street": "123",
"city": "Example City",
"state": "Example State",
"zip": 12345
}
}

This request would fail and return an error object as the payload contains a lot of invalid fields, such as email, password, age, and phone. Using the provided error object, you can handle the errors appropriately.

Simplifying Data Validation With Joi

Here you covered most of the basics of data validation using Joi. However, you can cover more advanced techniques and constraints in the Joi documentation.

Joi simplifies the data validation task in JavaScript, providing an intuitive solution that significantly improves the reliability and integrity of data stored in your application.

Schema Validation in Node.js With Joi (2024)

FAQs

Schema Validation in Node.js With Joi? ›

To validate data in Node. js using the Joi module, define a schema with specific validation rules. Use schema. validate(data) method to check if the data conforms to these rules, handling any validation errors that arise.

How to use joi for node api schema validation? ›

To begin, open your command line terminal and create a new project directory:
  1. mkdir joi-schema-validation.
  2. cd joi-schema-validation.
  3. npm init -y.
  4. npm install body-parser @1.18. ...
  5. nano app. ...
  6. // load app dependencies const express = require('express'); const logger = require('morgan'); const bodyParser = require('body-parser');
Sep 23, 2020

Is Joi good for validation? ›

Validating data is an important step in any application, especially as your application grows in complexity. One way to ensure that the data being passed around is valid and consistent is by using a data validation library, and one of the best options available is Joi.

What is the use of joi? ›

Joi allows the developers to build the Javascript blueprints and make sure that the application accepts the accurately formatted data. Easy to implement and easy to learn. Widely accepted and well-known package for data validation. Supports validation based on the schema.

How to do schema validation? ›

Specifying a schema​

Schemas are plain JavaScript objects that you pass to the checkSchema() function, where you specify which fields to validate as the keys, and the schema of the field as the value.

How to implement validation in NodeJS? ›

To do this we just add this piece of code to our bootstrap file where we create our Koa/Express app instance. const datalize = require('datalize'); // set datalize to throw an error if validation fails datalize. set('autoValidate', true); // only Koa // add to very beginning of Koa middleware chain app.

Which one is better, a JOI or Express-validator? ›

Sanitization: express-validator includes sanitization functions alongside validation functions. These functions allow developers to sanitize user inputs by removing or sanitizing potentially harmful content. joi, on the other hand, focuses solely on validation and does not provide built-in sanitization functions.

How do I add validation to API? ›

How to Implement Input Validation for APIs
  1. Validate Content-Type Header and Data Format. ...
  2. Prevent Entity Expansion. ...
  3. Limit the Size of Posted Data. ...
  4. Compare User Input Against Injection Flaws. ...
  5. Validate All Levels. ...
  6. Choose The Right Implementation For Your Programming Language. ...
  7. Use Allow Lists Instead Of Block Lists.
Nov 22, 2023

How do I add validation to a restful program? ›

Implementing Validations 🔐
  1. Step 1: Open the UserResources. ...
  2. Step 2: Add @Valid annotation. ...
  3. Step 3: Open Users. ...
  4. Step 4: Add @Size(min = 5) annotation just above the name variable. ...
  5. Step 5: Open RestClient in VS Code, select Send Request and send the POST request to the URL: localhost:3000/users. ...
  6. Send another POST request.
Mar 26, 2024

What is the best schema validation library? ›

Schema Validator Option: Zod

It's fast, it's easy to use, and it has no dependencies. Zod is based on the JSON Schema Validator (Joi) but with a different architecture. Zod can be used as a standalone package or with the Joi library. Zod supports static type inference, it works well with TypeScript.

What is the best JSON schema validator for nodejs? ›

Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: json-schema-benchmark - 50% faster than the second place. jsck benchmark - 20-190% faster. z-schema benchmark.

Is Joi real or fake? ›

Behind the scenes

Joi was a brand of DiJi designed by the Wallace Corporation.

How to validate using joi in NodeJS? ›

To validate data in Node. js using the Joi module, define a schema with specific validation rules. Use schema. validate(data) method to check if the data conforms to these rules, handling any validation errors that arise.

What is the alternative to Joi? ›

Explore other competing options and alternatives. Other important factors to consider when researching alternatives to Joi include ease of use and reliability. The best overall Joi alternative is monday.com. Other similar apps like Joi are ClickUp, Wrike, Cvent, and vFairs.

How to validate a file in JOI? ›

Let's see how to use Joi to validate javascript objects step by step in the Express application.
  1. Define package. json file: ...
  2. Installations: First, create the express application and Install the Joi library. ...
  3. Creating Schema: ...
  4. Constructor Support: ...
  5. Validating Nested Object: ...
  6. Joi As A Middleware:

How to do schema validation in API testing? ›

To validate the API schema in Postman, you need to write a test script in JavaScript that compares the API response against a predefined JSON schema. This is done using the pm. test function to create a test case, and then using pm. expect to assert that the API response adheres to the specified schema.

How to authenticate API requests in NodeJS? ›

Overview of authentication flow
  1. The user clicks a link to authorize your application.
  2. The user signs in to Intacct and grants access to their data.
  3. The authentication server responds by issuing an authorization code and redirecting the user to the registered callback URI.
Mar 14, 2024

How to validate JSON data in NodeJS? ›

How to Validate JSON Input with NodeJS (Schema)
  1. mkdir -p ~/projects. cd ~/projects. mkdir json-schema-101. cd json-schema-101.
  2. touch parser.js index.js. mkdir test-files. touch test-files/schema.json test-files/good.json test-files/bad.json.
  3. "type": "module",
  4. npm install --save ajv.

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Clemencia Bogisich Ret

Last Updated:

Views: 6065

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Clemencia Bogisich Ret

Birthday: 2001-07-17

Address: Suite 794 53887 Geri Spring, West Cristentown, KY 54855

Phone: +5934435460663

Job: Central Hospitality Director

Hobby: Yoga, Electronics, Rafting, Lockpicking, Inline skating, Puzzles, scrapbook

Introduction: My name is Clemencia Bogisich Ret, I am a super, outstanding, graceful, friendly, vast, comfortable, agreeable person who loves writing and wants to share my knowledge and understanding with you.