@exortek/express-mongo-sanitize
v2.0.2
Published
Express middleware for NoSQL injection prevention — sanitizes request data
Maintainers
Readme
@exortek/express-mongo-sanitize
Express middleware for NoSQL injection prevention. Sanitizes request body, query, and params to protect MongoDB queries from operator injection attacks.
📦 Installation
npm install @exortek/express-mongo-sanitizeyarn install @exortek/express-mongo-sanitizepnpm install @exortek/express-mongo-sanitize⚡ Quick Start
const express = require('express');
const mongoSanitize = require('@exortek/express-mongo-sanitize');
const app = express();
app.use(express.json());
app.use(mongoSanitize());
app.post('/login', (req, res) => {
// req.body is sanitized — { "$ne": "" } becomes { "ne": "" }
res.json(req.body);
});⚙️ Options
app.use(mongoSanitize({
replaceWith: '', // Replace matched chars with this string
removeMatches: false, // Remove entire key-value pair if pattern matches
sanitizeObjects: ['body', 'query'], // Request fields to sanitize
contentTypes: ['application/json', 'application/x-www-form-urlencoded'],
mode: 'auto', // 'auto' | 'manual'
skipRoutes: [], // Routes to skip (string or RegExp)
recursive: true, // Sanitize nested objects
maxDepth: null, // Max recursion depth (null = unlimited)
onSanitize: ({ key, originalValue, sanitizedValue }) => {
console.log(`Sanitized ${key}`);
}
}));For the full list of options, see the Core README.
🛠 Features
Route Parameter Sanitization
While body and query are sanitized automatically, route parameters can be sanitized using the paramSanitizeHandler:
const { paramSanitizeHandler } = require('@exortek/express-mongo-sanitize');
app.param('username', paramSanitizeHandler());
app.get('/user/:username', (req, res) => {
// GET /user/$admin → req.params.username is "admin"
res.json({ username: req.params.username });
});Manual Mode
If you need fine-grained control over when sanitization occurs:
app.use(mongoSanitize({ mode: 'manual' }));
app.post('/sensitive', (req, res) => {
req.sanitize(); // Manually trigger sanitization
res.json(req.body);
});Content-Type Guard
By default, only application/json and application/x-www-form-urlencoded bodies are sanitized to avoid corrupting binary data or file uploads. You can customize this:
app.use(mongoSanitize({ contentTypes: ['application/json', 'application/graphql'] }));📜 License
MIT — Created by ExorTek
