Express 4.x middleware to sanitize user-supplied data (req.body, req.query, req.params, req.headers) by stripping or replacing MongoDB operator injection characters ($ and .). This package is widely used to prevent NoSQL injection attacks, particularly the $where operator. Version 2.2.0 is stable, typed (TypeScript declarations included), and supports both CommonJS and ESM via Node >=10. Key differentiators: simple drop-in middleware, configurable replaceWith character, allowDots option for nested queries, onSanitize callback, and dry run mode. Alternatives like mongo-sanitize are lower-level; express-mongo-sanitize integrates directly with Express.
npm install express-mongo-sanitizeNo compatibility data collected yet for this library.
Verified import paths — ran on the pinned version, not inferred.
Express application that uses express-mongo-sanitize middleware to strip MongoDB operator injection characters from all request data.
If you relied on headers being unsanitized, set onSanitize or use replaceWith to control which fields are sanitized
Avoid allowDots unless targeting MongoDB >=3.6 or using replaceWith carefully
Ensure you test deeply nested payloads; the sanitize function recursively traverses objects
Use const mongoSanitize = require('express-mongo-sanitize') to get the middleware; for .sanitize, use const { sanitize } = require('express-mongo-sanitize')Remove dryRun: true in production or implement the onSanitize callback to log and still sanitize
Run 'npm install express-mongo-sanitize' and ensure your package.json includes it
Use 'const mongoSanitize = require('express-mongo-sanitize')' or update to ESM importUse 'import { sanitize } from 'express-mongo-sanitize'' instead of default importUse 'import type { SanitizeOptions }' for type-only import