Express Yup
express-yup
is a super light-weight Express middleware to easily validate the Express Request object against a Yup schema.
Yup is a leaner alternative to Joi, that also supports client-side validation and is the reason why this middleware was created in the first place - to easily share schemas between the client- and server-side.
If Joi is more your thing, then rather use the excellent express-validation library.
Installation
express-yup
has two peer-dependencies that you need to ensure is installed first: express
and yup
.
Install from NPM:
npm install express yup
If you are using TypeScript, you might want to install their type definition files as well:
npm install -D @types/express @types/yup
and then install express-yup
(it comes with its TypeScript types):
npm install express-yup
Usage
Add as middleware to your Express app as a whole if you want to validate all routes against a specific schema, or add individually to each route (more likely):
import express, { NextFunction, Request, Response } from 'express'
import bodyParser from 'body-parser'
import * as yup from 'yup'
import { validate } from 'express-yup'
const app = express()
app.use(bodyParser.json())
const authHeaderSchema = yup.object().shape({
headers: yup.object().shape({
authorization: yup
.string()
.matches(/^Bearer\s\w+$/)
.required(),
}),
})
app.use(validate(authHeaderSchema))
const routeSchema = yup.object().shape({
body: yup.object().shape({
hello: yup.string().required(),
bye: yup.string().required(),
}),
})
app.post(
'/some-route',
validate(routeSchema),
(req: Request, res: Response) => {
const { hello, bye } = req.body
}
)
app.use((error: Error, req: Request, res: Response, next: NextFunction) => {
if (error instanceof yup.ValidationError) {
res.status(400).json({ message: error.message })
return
}
res.status(500).json({ message: 'Internal Server Error' })
})
Licence
MIT