Express Middleware for Request Validation and Transformation
raw JSON →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.
Common errors
error body parameter "key1" is required ↓
.require() in the request body (e.g., JSON), query string, or URL parameters. error body parameter "key1" must be an array ↓
?key1[]=val1&key1[]=val2). error body parameter "key1" is not 24 characters ↓
.validate() middleware for that parameter. error body parameter "key1" must match /^hello/ ↓
.matches() middleware. Warnings
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. ↓
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. ↓
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. ↓
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. ↓
Install
npm install dat-middleware yarn add dat-middleware pnpm add dat-middleware Imports
- mw wrong
import mw from 'dat-middleware';correctconst mw = require('dat-middleware'); - Boom wrong
import { Boom } from 'dat-middleware';correctconst Boom = require('dat-middleware').Boom; - mw.body() / mw.query() / mw.params() wrong
app.use(body('key').require());correctapp.use(mw.body('key').require());
Quickstart
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`);
});