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

req-valid-express

v1.0.8

Published

Type-safe Express middleware for request validation (CJS, ESM, TS)

Downloads

23

Readme

req-valid-express

Middleware to validate body, query, and headers in Express applications.
Includes support for TypeScript, CommonJS, and ESM.

npm version npm downloads


You can read this in Spanish

📦 Installation

npm install req-valid-express

or with yarn:

yarn add req-valid-express

⚠️ Important!

Why use generated schemas?

To ensure compatibility and prevent unexpected bugs, all validation schemas should be created using the built-in generator — not written manually.

The generator is interactive and guides you step by step:

  1. Choose the path where the schema file will be saved.
  2. Select the file type (ESM, CommonJS, or TypeScript).
  3. Choose the file name (without extension)
  4. Configure the validation options for body, query, and headers.

You can generate schemas in two ways:

  1. Using npx (recommended, no install needed):

   npx validate-schema
  1. Adding a script to your package.json:
   "scripts": {
     "gen:schema": "validate-schema"
   }

Then run:

   npm run gen:schema

By generating schemas with the library:

  • ✅ You guarantee full support for sanitization, defaults, and types.
  • ✅ Future updates will remain backward-compatible.
  • ✅ You avoid subtle bugs from hand-written definitions.

👉 Always generate schemas instead of crafting them manually.


🚀 Basic Usage

In TypeScript (ESM)

Using validateBody:

import express from "express";
import { Validator } from "req-valid-express";
import type { Schema } from "req-valid-express";

const app = express();

// Example schema to validate the body
// ⚠️ Best practice: always use the schema generator, not manual objects
const userSchema: Schema = {
  body: {
    name: { 
      type: "string", 
      required: true, 
      sanitize: {
        trim: true,
        escape: true,
        lowercase: true
      }
    },
    age: { type: "number", default: 18 }
  }
};

// Basic usage: default maxDepth
app.post("/users", Validator.validateBody(userSchema.body), (req, res) => {
  res.json({ user: req.body });
});

// Advanced usage: configure maxDepth for deeply nested objects (e.g., MongoDB documents)
app.post("/deep-users", Validator.validateBody(userSchema.body, 15), (req, res) => {
  res.json({ user: req.body });
});


app.listen(3000, () => console.log("Server running at http://localhost:3000"));

In JavaScript (CommonJS)

Using validateQuery:

const express = require("express");
const { Validator } = require("req-valid-express");

const app = express();

// ⚠️ Best practice: always use the schema generator, not manual objects
const querySchema = {
  page: { type: "number", default: 1 },
  limit: { type: "number", default: 10 }
};

app.get("/items", Validator.validateQuery(querySchema), (req, res) => {
  res.json({ query: req.context.query });
});

app.listen(3000);

In JavaScript (ESM) -validateRegex

Using validateRegex:

import express from "express";
import { Validator } from "req-valid-express";

const app = express();

// Example regex to validate email
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

app.post("/users", Validator.validateRegex(
    emailRegex,
    "email", // Name of the field to validate
    "Please provide a valid email" // Optional custom message
  ), 
  (req, res) => {
    res.json({ user: req.body });
});

app.listen(3000, () => console.log("Server running at http://localhost:3000"));

In JavaScript (ESM) -paramId

Using paramId:

Note: You can use either the built-in validReg (predefined regex) or an external validation method.

import express from "express";
import { Validator } from "req-valid-express";
import { validate as uuidValidate } from "uuid";

const app = express();

app.get("/users/:id", Validator.paramId(
  "id", // The parameter name to validate
  Validator.ValidReg.UUID // Built-in regex validation
), (req, res) => {
  res.json({ user: req.body });
});

app.put("/users/:userId", Validator.paramId(
  "userId",   // The parameter name to validate
  uuidValidate // External validation method
), (req, res) => {
  res.json({ user: req.body });
});

app.listen(3000, () => console.log("Server running at http://localhost:3000"));

📖 API

The main class is Validator. It provides methods to validate different parts of the request:

  • validateBody(schema)
  • validateQuery(schema)
  • validateHeaders(schema)
  • validateRegex(regex, 'field', message(optional)): validates a specific body field against a regex
  • paramId('param', method): validates request params (req.params)
  • validReg: provides built-in regex for paramId (optional)

Any field not declared in the schema will be removed. Only valid fields or those with default values will pass through the validator.

Each schema supports:

  • type: "string", "int", "float", "boolean"
  • default: default value if missing
  • sanitize: sanitizers (trim, escape, lowercase, etc.)

Example schema with regex and sanitization:

const schema = {
  email: { type: "string",  sanitize: { trim: true } }
};

🧩 Express.Request Extension

The library adds a context property to the Express req object, where validated values are stored.

declare global {
  namespace Express {
    interface Request {
      context: {
        body?: any;
        query?: any;
        headers?: any;
      };
    }
  }
}

This allows you to safely use:

req.context.query
req.context.headers

with proper typing in TypeScript.


📄 License

MIT © 2025 - antorrg

📜 Changelog

See CHANGELOG.md for a complete list of changes.

💬 Feedback and Support

Do you have comments, ideas, or found a bug?
Your feedback is very important! You can:

Thank you for helping improve req-valid-express 🙌