{"id":17617,"library":"express-joi-middleware","title":"Express Joi Middleware","description":"express-joi-middleware is an Express.js middleware designed to integrate Hapi.js's Joi validation library seamlessly into Express applications. Currently at its first stable release, version 1.0.0, this package provides robust request body, query, parameters, and headers validation against user-defined Joi schemas. Its key differentiators include extensive customization options, such as the ability to supply a specific Joi instance (useful for managing Joi versions or custom extensions), fine-grained control over error response handling (either automatically sending a 400 Bad Request or `next`ing the Joi error for custom handling), and the choice to override the `req.body` or create a new `req.validated` key with the processed data. The project is new, so a specific release cadence has not yet been established, but it focuses on providing a flexible and configurable validation layer.","status":"active","version":"1.0.0","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/oxyno-zeta/express-joi-middleware","tags":["javascript","Express","Joi","Middleware","Validator","Validation"],"install":[{"cmd":"npm install express-joi-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add express-joi-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add express-joi-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core dependency for schema definition and validation. The middleware relies on Joi for all validation logic.","package":"joi","optional":false},{"reason":"The package is an Express.js middleware and requires an Express application to function.","package":"express","optional":false}],"imports":[{"note":"This package is CommonJS-only as of v1.0.0. Named imports or default ESM imports are not supported.","wrong":"import expressJoiMiddleware from 'express-joi-middleware';","symbol":"expressJoiMiddleware","correct":"const expressJoiMiddleware = require('express-joi-middleware');"},{"note":"While this package uses Joi internally, you must explicitly import Joi in your application to define validation schemas for the middleware.","wrong":"import Joi from 'joi';","symbol":"Joi","correct":"const Joi = require('joi');"}],"quickstart":{"code":"const express = require('express');\nconst bodyParser = require('body-parser');\nconst Joi = require('joi'); // Crucial: Joi must be imported by the user\nconst expressJoiMiddleware = require('express-joi-middleware');\n\nconst app = express();\n\napp.use(bodyParser.json());\n\nconst userSchema = {\n    body: {\n        id: Joi.string().guid({ version: 'uuidv4' }).required(),\n        name: Joi.string().min(3).max(30).required(),\n        email: Joi.string().email().required()\n    },\n    params: {\n        userId: Joi.string().guid({ version: 'uuidv4' }).required()\n    }\n};\n\nconst options = {\n    wantResponse: true // Middleware sends 400 Bad Request automatically\n};\n\n// Example: Validating a POST request body\napp.post('/users', expressJoiMiddleware(userSchema, options), (req, res) => {\n    // req.validated will contain the validated and transformed body/query/params\n    res.status(201).json({ message: 'User created successfully', data: req.validated });\n});\n\n// Example: Validating a GET request with path parameters\napp.get('/users/:userId', expressJoiMiddleware(userSchema, options), (req, res) => {\n    res.json({ message: `Fetching user ${req.validated.userId}`, user: { id: req.validated.userId, name: 'Example User' } });\n});\n\n// Custom error handler for Joi errors if wantResponse is false or for other errors\napp.use((err, req, res, next) => {\n    if (err.isJoi) {\n        console.error('Joi validation error:', err.details);\n        return res.status(400).json(err.details);\n    }\n    console.error('Internal server error:', err);\n    res.status(500).send('Internal Server Error');\n});\n\napp.listen(8080, () => {\n    console.log('Server listening on http://localhost:8080');\n});","lang":"javascript","description":"This quickstart demonstrates how to set up `express-joi-middleware` in an Express application to validate request bodies and path parameters using Joi schemas, including explicit Joi import and an error handling middleware."},"warnings":[{"fix":"Always include `const Joi = require('joi');` at the top of your file when defining Joi schemas for `express-joi-middleware`.","message":"The quickstart example in the README omits the explicit `require('joi')` statement, which is essential for defining Joi schemas. Without it, you will encounter runtime errors indicating `Joi is not defined`.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Either set `wantResponse: true` in the middleware options for automatic 400 Bad Request responses, or implement an Express error-handling middleware (`app.use((err, req, res, next) => { ... })`) to specifically handle `err.isJoi` validation errors.","message":"By default (`wantResponse: false`), `express-joi-middleware` will `next` Joi validation errors to the next middleware. If you do not have a custom error-handling middleware set up to catch `err.isJoi` errors, these errors will propagate and potentially crash your application or result in generic 500 errors.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Use `const expressJoiMiddleware = require('express-joi-middleware');` for importing the middleware.","message":"As of version 1.0.0, this package is exclusively CommonJS. Attempting to use ESM `import` statements will result in a runtime error.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Add `const Joi = require('joi');` at the top of the file where your Joi schemas are defined.","cause":"The Joi object was used to define a schema (e.g., `Joi.string()`) without being explicitly imported into the file.","error":"ReferenceError: Joi is not defined"},{"fix":"Ensure you are calling `expressJoiMiddleware(schemaObject, optionsObject)` to return the middleware function, e.g., `app.post('/path', expressJoiMiddleware(mySchema), (req, res) => ...);`.","cause":"The `expressJoiMiddleware` function was called incorrectly or not at all. It expects two arguments: a schema object and an optional options object.","error":"TypeError: app.use() requires a middleware function but got a Object"},{"fix":"Review the Joi schema definition and the input data being sent to ensure they match the expected validation rules. The error message from Joi often provides specific details on what failed.","cause":"A Joi validation rule (e.g., `Joi.ip()`) failed for an input field.","error":"Error: Invalid IP address: 127.0.0.1 (Joi error)"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}