Celebrate

15.0.3 · active · verified Wed Apr 22

Celebrate is a robust Express.js middleware designed for integrating Joi validation seamlessly into web applications. It allows developers to define validation schemas for various parts of an incoming request, including `req.params`, `req.headers`, `req.query`, `req.body`, `req.cookies`, and `req.signedCookies`. The library is currently stable at version 15.0.3 and undergoes regular maintenance with notable major version updates introducing breaking changes (e.g., v15, v14, v13, v8, v4, v3, v2). A key differentiator is its formal dependency on `joi`, ensuring a consistent and up-to-date Joi version is always used and also exported for consumer compatibility. It aims to simplify input validation in Express routes, providing a consistent error handling mechanism before any route handler is executed.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic Express setup with `celebrate` middleware for input validation on a POST route. It validates `req.body` and `req.headers` using Joi schemas and includes the `errors()` middleware for consistent error responses. It also shows how to access the `Joi` instance exported by `celebrate` for custom schema definitions.

import express from 'express';
import bodyParser from 'body-parser';
import { celebrate, Joi, errors, Segments } from 'celebrate';

const app = express();

app.use(bodyParser.json());

app.post('/signup', celebrate({
  [Segments.BODY]: Joi.object().keys({
    name: Joi.string().required().min(3).max(50),
    email: Joi.string().email().required(),
    age: Joi.number().integer().min(18).max(120),
    role: Joi.string().valid('user', 'admin').default('user')
  }),
  [Segments.HEADERS]: Joi.object({
    authorization: Joi.string().required()
  }).unknown(true) // Allow other headers
}), (req, res) => {
  // At this point, req.body and req.headers have been validated and 
  // req.body.role is set to 'user' if not provided.
  console.log('Validated body:', req.body);
  console.log('Validated headers:', req.headers.authorization);
  res.status(200).send('Signup successful!');
});

// Error handling middleware from celebrate
app.use(errors());

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

// Example of accessing the exported Joi instance directly
const myCustomSchema = Joi.object({
  customField: Joi.string().alphanum().min(3).required()
});

// To test, send a POST request to http://localhost:3000/signup 
// with a JSON body like: 
// {"name": "Test User", "email": "test@example.com", "age": 30}
// and an 'Authorization' header. A missing 'name' or 'email' will fail validation.

view raw JSON →