How to Use Joi for Validation in Express: Simple Guide
Use
Joi to define a schema for your data, then validate incoming requests in Express middleware by calling schema.validate(). If validation fails, respond with an error; otherwise, continue to your route handler.Syntax
To use Joi for validation in Express, first define a Joi schema describing the expected data shape. Then, in your route middleware, call schema.validate(req.body) to check the data. If validation passes, proceed; if it fails, send an error response.
- schema: Defines rules for data fields.
- validate(data): Checks data against schema.
- error: Contains validation errors if any.
javascript
import Joi from 'joi'; const schema = Joi.object({ fieldName: Joi.string().required(), anotherField: Joi.number().min(0) }); // Inside an Express route handler or middleware const { error, value } = schema.validate(req.body); if (error) { // handle error } else { // proceed with valid data }
Example
This example shows a simple Express server that validates a JSON body with Joi before responding. It checks that name is a required string and age is an optional number above 0.
javascript
import express from 'express'; import Joi from 'joi'; const app = express(); app.use(express.json()); const userSchema = Joi.object({ name: Joi.string().required(), age: Joi.number().min(1) }); app.post('/user', (req, res) => { const { error, value } = userSchema.validate(req.body); if (error) { return res.status(400).json({ error: error.details[0].message }); } res.json({ message: 'User data is valid', data: value }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
Common Pitfalls
Common mistakes when using Joi with Express include:
- Not calling
express.json()middleware, soreq.bodyis undefined. - Ignoring the
errorfromschema.validate()and proceeding with invalid data. - Using
Joi.validate()(legacy) instead ofschema.validate(). - Not returning or ending the response after sending an error, causing the request to hang.
javascript
/* Wrong way: Missing express.json() middleware */ app.post('/user', (req, res) => { const { error } = userSchema.validate(req.body); // req.body is undefined if (error) { res.status(400).send(error.details[0].message); } res.send('Done'); // This runs even if error }); /* Right way: */ app.use(express.json()); app.post('/user', (req, res) => { const { error } = userSchema.validate(req.body); if (error) { return res.status(400).send(error.details[0].message); // return stops further code } res.send('Done'); });
Quick Reference
Here is a quick summary of key Joi validation methods useful in Express:
| Joi Method | Purpose | Example |
|---|---|---|
| Joi.string() | Validates a string | Joi.string().min(3).required() |
| Joi.number() | Validates a number | Joi.number().min(0) |
| Joi.object() | Defines an object schema | Joi.object({ name: Joi.string() }) |
| schema.validate(data) | Validates data against schema | const { error } = schema.validate(req.body) |
| Joi.array() | Validates an array | Joi.array().items(Joi.string()) |
Key Takeaways
Always define a Joi schema matching your expected data shape before validation.
Use express.json() middleware to parse JSON bodies before validating.
Call schema.validate(req.body) and handle errors by sending a response and stopping further processing.
Return or end the response immediately after sending validation errors to avoid hanging requests.
Use Joi's rich API to create precise validation rules for your Express routes.