{"id":17437,"library":"express-joi-validations","title":"Express Joi Validations","description":"express-joi-validations is an Express.js middleware package designed to streamline request validation using the Joi schema validation library. Currently at version 0.1.0, it provides a flexible mechanism to validate various parts of an incoming HTTP request, including headers, URL parameters, query strings, and the request body. While its last publish was over two years ago (as of May 2024), suggesting a maintenance-only status rather than active development, it offers both a consolidated validation middleware for multiple request parts and individual helper functions (e.g., `validateBody`, `validateParams`) for more granular control. Key differentiators include its explicit handling of validated data through `request.validationValues` and the ability to optionally overwrite the original request data or throw errors for integration with asynchronous error handling. This allows developers to strictly enforce data integrity at the API layer.","status":"maintenance","version":"0.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/mattiamalonni/express-joi-validations","tags":["javascript","express-middleware","validation-middleware","joi-validation","request-validation","input-validation","data-validations","schema-validation","input-sanitization","typescript"],"install":[{"cmd":"npm install express-joi-validations","lang":"bash","label":"npm"},{"cmd":"yarn add express-joi-validations","lang":"bash","label":"yarn"},{"cmd":"pnpm add express-joi-validations","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core web framework the middleware integrates with.","package":"express","optional":false},{"reason":"Primary schema validation library used for defining validation rules.","package":"joi","optional":false}],"imports":[{"note":"This is the default export for the 'out of the box' combined validation middleware.","wrong":"const validate = require('express-joi-validations');","symbol":"validate","correct":"import validate from 'express-joi-validations';"},{"note":"Used to initialize the middleware with custom global configurations like `throwErrors` or `overwriteRequest`.","wrong":"const { expressJoiValidations } = require('express-joi-validations');","symbol":"expressJoiValidations","correct":"import { expressJoiValidations } from 'express-joi-validations';"},{"note":"Specific helper functions like `validateBody`, `validateParams`, `validateQuery`, `validateHeaders` are named exports. `Joi` itself is also exported from the package for convenience.","wrong":"import validateBody from 'express-joi-validations/validateBody';","symbol":"validateBody","correct":"import { validateBody } from 'express-joi-validations';"},{"note":"The package re-exports the Joi instance it uses, ensuring consistency. It's generally recommended to import Joi directly from the 'joi' package for flexibility with versions, but this is provided as a convenience.","wrong":"import Joi from 'joi';","symbol":"Joi","correct":"import { Joi } from 'express-joi-validations';"}],"quickstart":{"code":"import express, { Request, Response, NextFunction } from 'express';\nimport { Joi, validateHeaders, validateParams, validateBody, expressJoiValidations } from 'express-joi-validations';\n\nconst app = express();\napp.use(express.json()); // Required to parse JSON request bodies\n\n// Optionally configure global settings for all validations\napp.use(expressJoiValidations({ throwErrors: true, overwriteRequest: false }));\n\nconst userToken = Joi.object({\n  authorization: Joi.string().regex(/^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_.+/=]*$/).required(),\n});\n\nconst postId = Joi.object({\n  id: Joi.string().hex().length(24).required(),\n});\n\nconst postBody = Joi.object({\n  title: Joi.string().required().trim().min(5),\n  content: Joi.string().required().trim().min(10),\n  tags: Joi.array().items(Joi.string()).optional()\n});\n\n// Example route with chained validations\napp.put(\n  '/posts/:id',\n  validateHeaders(userToken),\n  validateParams(postId),\n  validateBody(postBody, { allowUnknown: false }), // Joi options can be passed per validator\n  (req: Request, res: Response) => {\n    // If throwErrors is true, an error handler middleware will catch validation errors.\n    // Otherwise, validation results (errors, values) are on req.validationErrors and req.validationValues\n    const validatedData = (req as any).validationValues; // Cast to 'any' or extend Request type if not using `overwriteRequest`\n    res.status(200).json({ message: 'Post updated successfully', data: validatedData });\n  }\n);\n\n// Global error handler for thrown validation errors (if throwErrors: true)\napp.use((err: any, req: Request, res: Response, next: NextFunction) => {\n  if (err && err.error && err.error.isJoi) {\n    // A Joi validation error\n    return res.status(400).json({ type: err.type, message: err.error.toString() });\n  }\n  next(err); // Pass on to other error handlers\n});\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => console.log(`Server running on port ${PORT}`));","lang":"typescript","description":"This quickstart demonstrates setting up an Express server with multiple Joi validations for a PUT request, including headers, parameters, and body, and integrates a basic error handling middleware."},"warnings":[{"fix":"Initialize `expressJoiValidations({ throwErrors: true })` globally or pass `{ throwErrors: true }` as a Joi option to individual validation helper functions. Consider using `express-async-errors` alongside this if using asynchronous routes.","message":"By default, validation errors are not thrown. Instead, they are attached to `request.validationErrors`. To throw errors for standard Express error handling, you must set the `throwErrors: true` option during middleware initialization or per helper function.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Either set `overwriteRequest: true` in the middleware configuration if you want the original request properties to be mutated, or consistently access validated data from `req.validationValues`.","message":"The package can optionally overwrite the original `req.body`, `req.query`, etc., with the validated data. If `overwriteRequest` is `false` (default), validated data is available in `request.validationValues`, requiring explicit access or type assertions in TypeScript.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Exercise caution when upgrading `express` or `joi` dependencies. Thoroughly test existing validations after dependency updates. Consider alternative, more actively maintained Joi-Express validation libraries if long-term stability with latest versions is critical.","message":"This package is at version 0.1.0 and has not been updated in over two years (as of May 2024). Compatibility with newer versions of Joi or Express, especially those introducing breaking changes, might not be actively maintained, potentially leading to unexpected behavior or security vulnerabilities with future dependency updates.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure that the client sends a non-empty request body if required by the schema, or update the Joi schema to allow optional fields or an empty object using `.optional()` or `.allow({})`.","cause":"An empty request body was sent, but the Joi schema for `body` marked all fields as required, or didn't allow for an empty object.","error":"JoiValidationError: \"body\" is not allowed to be empty"},{"fix":"Verify that `throwErrors: true` is configured where validation is performed, allowing the `express-joi-validations` middleware to throw Joi-specific errors that your error handler can then catch and process.","cause":"This typically occurs if the error handling middleware expects a Joi error structure but receives a different type of error, often because `throwErrors` was not set to `true`.","error":"TypeError: Cannot read properties of undefined (reading 'isJoi')"},{"fix":"Ensure that the schema is correctly defined using `Joi.object({})`, `Joi.string()`, etc., and is a valid Joi schema object before passing it to the validation middleware.","cause":"The Joi schema object passed to a validation helper (e.g., `validateBody`) is not a valid Joi schema instance.","error":"Error: Invalid Joi Schema"}],"ecosystem":"npm","meta_description":null}