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

zsanitizer

v1.1.2

Published

A robust, zero-dependency sanitizer for Node.js to prevent XSS and other attacks by safely cloning and cleaning input data with customizable rules.

Readme

zsanitizer 🛡️

A robust, zero-dependency sanitizer for Node.js to prevent XSS, path traversal, and other injection attacks by safely cloning and cleaning user input with customizable rules.

CI NPM version

zsanitizer ensures that data processed by your application is safe. It deeply traverses objects and arrays, sanitizing strings, handling file-like objects (e.g., from Multer), and preventing common vulnerabilities. It never mutates the original input.

Features

  • Deep Sanitization: Recursively sanitizes nested objects and arrays.
  • Customizable Rules: Define your own sanitization logic for strings, numbers, and more.
  • XSS Protection: Escapes HTML in strings to prevent Cross-Site Scripting.
  • Path Traversal Prevention: Sanitizes filenames in file-like objects.
  • Safe Cloning: Handles circular references gracefully and removes functions.
  • Type Preservation: Correctly handles Buffer, Date, and RegExp objects.
  • Zero Dependencies: Lightweight and secure.
  • TypeScript Native: Fully written in TypeScript with types included.

Installation

npm install zsanitizer

Basic Usage

The simplest way to use the package is to import the default sanitize function, which uses sensible defaults.

import { sanitize } from "zsanitizer";

const maliciousInput = {
  comment: '<script>alert("XSS")</script>',
  attachment: {
    originalname: '../../../../../etc/passwd',
    buffer: Buffer.from('file content'),
  },
};

const sanitized = sanitize(maliciousInput);

console.log(sanitized);
/*
{
  comment: '&lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;',
  attachment: {
    originalname: '.._.._.._.._.._etc_passwd',
    buffer: <Buffer ...>
  }
}
*/

Advanced Usage

Defining Custom Sanitization Rules

For ultimate control, you can define your own sanitization logic for specific data types using the customSanitizers option.

Important: When you provide a custom sanitizer for a type (e.g., string), it replaces the built-in logic for that type (like trim and escapeHtml). This allows you to implement any logic you need, such as profanity filtering, custom formatting, or number clamping.

import { createSanitizer } from "zsanitizer";

// Custom rule to replace bad words in strings
const profanityFilter = (value: string): string => {
  return value.trim().replace(/darn/gi, "****");
};

// Custom rule to ensure numbers are within a specific range (0-100)
const clampNumber = (value: number): number => {
  return Math.max(0, Math.min(100, value));
};

const customSanitizer = createSanitizer({
  escapeHtml: false, // Disable default escaping to let our filter run
  customSanitizers: {
    string: profanityFilter,
    number: clampNumber,
  },
});

const userInput = {
  comment: "  Well darn, this is some user input.  ",
  rating: 150,
  score: -10,
  age: 30,
};

const sanitized = customSanitizer.sanitize(userInput);
console.log(sanitized);
/*
{
  comment: 'Well ****, this is some user input.',
  rating: 100,
  score: 0,
  age: 30
}
*/

Express + Multer Example

zsanitizer is perfect for cleaning req.body and req.file in an Express application.

import express from "express";
import multer from "multer";
import { sanitize } from "zsanitizer";

const app = express();
const upload = multer({ storage: multer.memoryStorage() });

// Middleware to sanitize all incoming data
app.use((req, res, next) => {
  if (req.body) req.body = sanitize(req.body);
  if (req.query) req.query = sanitize(req.query);
  if (req.params) req.params = sanitize(req.params);
  if (req.file) req.file = sanitize(req.file);
  if (req.files) req.files = sanitize(req.files);
  next();
});

app.post("/upload", upload.single("document"), (req, res) => {
  // req.body and req.file are safely sanitized
  res.json({
    status: "success",
    body: req.body,
    file: req.file,
  });
});

app.listen(3000, () => console.log("Server running on port 3000"));

API Reference

sanitize(input: any): any
The default sanitizer instance with standard options.

createSanitizer(options?: SanitizationOptions): Sanitizer
Creates a new Sanitizer instance with custom options.

SanitizationOptions

| Option | Type | Default | Description | | ------------------ | -----------------: | :-----: | ------------------------------------------------------------------------------------------------------------------- | | trim | boolean | true | If true, trims leading/trailing whitespace from strings. (Ignored if a custom string sanitizer is provided.) | | escapeHtml | boolean | true | If true, escapes HTML special characters. (Ignored if a custom string sanitizer is provided.) | | allowNull | boolean | false | If false, null values are converted to empty strings (''). If true, null values are preserved. | | sanitizeFiles | boolean | true | If true, detects and sanitizes file-like objects (e.g., from Multer). | | maxStringLength | number | 10000 | The maximum allowed length for strings. (Ignored if a custom string sanitizer is provided.) | | customSanitizers | CustomSanitizers | {} | An object with functions to handle specific types, replacing the default logic. Supported keys: string, number. |

Limitations

  • This is not an antivirus. It does not scan file contents for malware.
  • It is not a data validation library. It does not check if a string is a valid email or if a number is within a specific range. Use libraries like zod or joi for validation.