Express Middleware for Request Validation and Transformation

raw JSON →
1.10.4 verified Thu Apr 23 auth: no javascript maintenance

dat-middleware is an Express.js middleware library that provides a fluent and declarative API for common request data operations. It focuses on validating and transforming `req.body`, `req.query`, and `req.params` against various criteria such as required fields, data types (string, number, array, boolean, object, function), specific class instances (`instanceOf`), and regular expressions (`matches`). Developers can also integrate custom validation logic using the `validate()` method. Upon validation failure, the middleware automatically calls `next()` with a 400 Bad Request error object generated by `spumko/boom`, simplifying error handling. The current stable version is 1.10.4. Given its last update several years ago, it operates primarily in a maintenance mode, offering a stable but not actively developed solution for Express input validation. Its key differentiator is the chaining syntax for defining validation rules directly within the middleware stack.

error body parameter "key1" is required
cause A parameter specified by `.require()` was missing from `req.body`, `req.query`, or `req.params`.
fix
Ensure the client sends all parameters specified by .require() in the request body (e.g., JSON), query string, or URL parameters.
error body parameter "key1" must be an array
cause A parameter that was expected to be an array type did not receive an array.
fix
Verify that the client sends the specified parameter as a valid JSON array or an array in query string/URL parameters (e.g., ?key1[]=val1&key1[]=val2).
error body parameter "key1" is not 24 characters
cause A custom validation function provided to `.validate()` returned a Boom error because the input value did not meet its specified criteria.
fix
Adjust the client input to satisfy the custom validation logic defined by the .validate() middleware for that parameter.
error body parameter "key1" must match /^hello/
cause A string parameter did not conform to the regular expression pattern defined in the `.matches()` middleware.
fix
Ensure the string value for the parameter precisely matches the regular expression pattern specified in the .matches() middleware.
gotcha dat-middleware is a CommonJS module and requires explicit configuration (e.g., bundler support or a wrapper) to be used directly in an ES Module-only Node.js environment or browser builds.
fix For Node.js ESM projects, consider using a CommonJS wrapper or a different, modern validation library. For browser builds, ensure your bundler (webpack, rollup) is configured to handle CommonJS modules.
deprecated The library internally uses 'spumko/boom' (now '@hapi/boom'), an older version of the Boom error handling library. While functional, it might not be compatible with newer versions of Boom or related Hapi ecosystem tools.
fix Be aware that custom error handling or integration with other Hapi libraries might require adapting to the older Boom version. Consider migrating to a more actively maintained validation library for new projects.
gotcha Error handling relies on Express's standard next(err) mechanism. The errors are Boom objects (HTTP 400). If you have custom error middleware, ensure it can properly interpret and respond to these error types.
fix Implement an Express error handling middleware function (e.g., `app.use(function (err, req, res, next) { ... })`) that specifically checks for Boom errors (e.g., `err.isBoom`) to extract status codes and messages correctly.
gotcha The `instanceOf` validation method relies on JavaScript's prototype chain. This might not behave as expected when dealing with objects passed across different realms (e.g., if objects are deserialized from JSON or come from different Node.js contexts), or if the `Class` constructor is not the exact one used to create the instance.
fix For complex object validation, prefer `validate()` with a custom function that performs structural checks, or use a dedicated schema validation library that offers more robust type and structure validation.
npm install dat-middleware
yarn add dat-middleware
pnpm add dat-middleware

This quickstart sets up an Express server with `dat-middleware` to validate request body parameters for a `/user` endpoint, demonstrating required fields, type checks, regex matching, and custom validation.

var mw = require('dat-middleware');
var express = require('express');
var app = express();
var bodyParser = require('body-parser'); // Needed for req.body

app.use(bodyParser.json()); // To parse JSON bodies

// Custom validation function example: ensures a string is exactly 24 characters
function is24Chars (val) {
  if (typeof val !== 'string') {
    return mw.Boom.badRequest('must be a string');
  }
  return (val.length !== 24) ?
    mw.Boom.badRequest('is not 24 characters'):
    null; // pass
}

// Define a route that uses dat-middleware for validation and transformation
app.post('/user',
  // Require 'name' and 'age' in the request body
  mw.body('name', 'age').require(),
  // Ensure 'age' is a number
  mw.body('age').number(),
  // Ensure 'id' matches a specific regular expression (e.g., MongoDB ObjectID format)
  mw.body('id').matches(/^[a-fA-F0-9]{24}$/), 
  // Apply custom validation to 'description'
  mw.body('description').validate(is24Chars),
  // If all validations pass, process the request
  function (req, res) {
    res.json({
      message: 'User data validated and processed!',
      data: req.body
    });
  }
);

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
  console.log('Test with valid data:');
  console.log(`  curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe","age":30,"id":"60c72b2f9c1d44001c8c4e4e", "description": "This is a 24 char string"}' http://localhost:${PORT}/user`);
  console.log('Test with invalid age (not a number):');
  console.log(`  curl -X POST -H "Content-Type: application/json" -d '{"name":"Jane Doe","age":"thirty","id":"60c72b2f9c1d44001c8c4e4e", "description": "This is a 24 char string"}' http://localhost:${PORT}/user`);
  console.log('Test with missing name:');
  console.log(`  curl -X POST -H "Content-Type: application/json" -d '{"age":30,"id":"60c72b2f9c1d44001c8c4e4e", "description": "This is a 24 char string"}' http://localhost:${PORT}/user`);
});