npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@exortek/express-mongo-sanitize

v1.1.1

Published

A comprehensive Express middleware designed to protect your No(n)SQL queries from injection attacks by sanitizing request data. This middleware provides flexible sanitization options for request bodies, parameters, and query strings.

Downloads

2,795

Readme

@exortek/express-mongo-sanitize

A comprehensive Express middleware designed to protect your No(n)SQL queries from injection attacks by sanitizing request data.
This middleware provides flexible sanitization options for request bodies and query strings, and an optional handler for route parameters.

Compatibility

| Middleware version | Express version | |--------------------|:---------------:| | ^1.x | ^4.x | | ^1.x | ^5.x |

Features

  • Automatic sanitization of req.body and req.query by default
  • Supports deep/nested objects, arrays, and string transformation
  • Allows custom sanitizer logic, key allow/deny lists, skip routes, and more
  • Route params (req.params) can be sanitized with an explicit helper (see below)

Installation

yarn add @exortek/express-mongo-sanitize
# or
npm install @exortek/express-mongo-sanitize

Usage

Basic usage

const express = require('express');
const expressMongoSanitize = require('@exortek/express-mongo-sanitize');

const app = express();
app.use(express.json());

// Body and query are sanitized automatically:
app.use(expressMongoSanitize());

app.post('/submit', (req, res) => {
  res.json(req.body);
});

Sanitizing Route Params (req.params)

By default, only body and query are sanitized.
If you want to sanitize route parameters (req.params),
use the exported paramSanitizeHandler with Express's app.param or router.param:

// Route parameter sanitization (recommended way):
app.param('username', expressMongoSanitize.paramSanitizeHandler());

// Example route:
app.get('/user/:username', (req, res) => {
  res.json({ username: req.params.username });
});

Note:

  • You can attach this for any route param, e.g. 'id', 'slug', etc.
  • This gives you full control and doesn't require the middleware to know your routes.

Options

| Option | Type | Default | Description | |-------------------|----------|-------------------------------------|---------------------------------------------------------------------| | replaceWith | string | '' | String to replace matched patterns | | removeMatches | boolean | false | Remove values matching patterns entirely | | sanitizeObjects | string[] | ['body', 'query'] | List of request objects to sanitize | | mode | string | 'auto' | 'auto' for automatic, 'manual' for explicit req.sanitize() call | | skipRoutes | string[] | [] | List of paths to skip (e.g. ['/health']) | | customSanitizer | function | null | Custom sanitizer function, overrides built-in sanitizer | | recursive | boolean | true | Recursively sanitize nested values | | removeEmpty | boolean | false | Remove empty values after sanitization | | patterns | RegExp[] | See source code | Patterns to match for sanitization | | allowedKeys | string[] | [] | Only allow these keys (all if empty) | | deniedKeys | string[] | [] | Remove these keys (none if empty) | | stringOptions | object | See below | String transform options (trim, lowercase, maxLength) | | arrayOptions | object | See below | Array handling options (filterNull, distinct) | | debug | object | { enabled: false, level: "info" } | Enables debug logging for middleware internals. |

stringOptions default:

{
  trim: false,
  lowercase: false,
  maxLength: null
}

arrayOptions default:

{
  filterNull: false,
  distinct: false
}

Manual Mode

If you set mode: 'manual', the middleware will not sanitize automatically.
Call req.sanitize() manually in your route:

app.use(expressMongoSanitize({ mode: 'manual' }));

app.post('/manual', (req, res) => {
  req.sanitize({ replaceWith: '_' }); // custom options are supported here
  res.json(req.body);
});

Skipping Routes

Skip certain routes by adding their paths to skipRoutes:

app.use(expressMongoSanitize({ skipRoutes: ['/skip', '/status'] }));

// These routes will NOT be sanitized

Custom Sanitizer

Use a completely custom sanitizer function:

app.use(expressMongoSanitize({
  customSanitizer: (data, options) => {
    // Your custom logic
    return data;
  }
}));

Route Parameter Sanitization

By default, only body and query are sanitized. If you want to sanitize route parameters (req.params),
use the helper function with app.param or router.param:

app.param('username', expressMongoSanitize.paramSanitizeHandler());

This ensures that, for example, /user/$admin will be returned as { username: 'admin' }
in your handler.


TypeScript

Type definitions are included.
You can use this plugin in both CommonJS and ESM projects.


Advanced Usage

Custom Sanitizer per Route

You can override sanitizer options or use a completely custom sanitizer per route:

app.post('/profile', (req, res, next) => {
  req.sanitize({
    customSanitizer: (data) => {
      // For example, redact all strings:
      if (typeof data === 'string') return '[REDACTED]';
      return data;
    }
  });
  res.json(req.body);
});

Debugging & Logging

You can enable debug logs to see the internal operation of the middleware.
Useful for troubleshooting or when tuning sanitization behavior.

app.use(
  expressMongoSanitize({
    debug: {
      enabled: true,         // Turn on debug logs
      level: 'debug',        // Log level: 'error' | 'warn' | 'info' | 'debug' | 'trace'
      logSkippedRoutes: true // (optional) Log when routes are skipped
    },
    // ...other options
  })
);

Logging Levels

| Level | Description | |---------|--------------------------------------| | error | Logs only errors | | warn | Logs warnings and errors | | info | Logs informational messages | | debug | Logs detailed debug information | | trace | Logs very detailed trace information |

Using with Router

const router = express.Router();
router.use(expressMongoSanitize());
// You can use paramSanitizeHandler on router params as well:
router.param('userId', expressMongoSanitize.paramSanitizeHandler());

Troubleshooting

Route parameters are not being sanitized

By default, only body and query are sanitized.
To sanitize route parameters, use:

app.param('username', expressMongoSanitize.paramSanitizeHandler());

Skipping specific routes doesn't work as expected

Make sure you use the exact path as in your route definition,
and that you apply the middleware before your routes.


My request is not being sanitized

  • Ensure your route handler is after the middleware in the stack.
  • If you are using mode: 'manual', you must call req.sanitize() yourself.

For more troubleshooting, open an issue at Github Issues


License

MIT

Copyright © 2025 ExorTek