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 🙏

© 2026 – Pkg Stats / Ryan Hefner

express-zod-guard

v1.0.0

Published

Lightweight Express middleware for validating request body, query, and params using Zod with clean error handling.

Readme

Validation Request Middleware

Express middleware for validating request data using Zod schemas with automatic HTTP exception handling.

Dependencies

import { HTTPException } from 'express-http-exception';
import { StatusCodes } from 'http-status-codes';
import { NextFunction, Request, Response } from 'express';
import { ZodError, ZodType } from 'zod';

Type Definition

type ValidationSchemas = {
  body?: ZodType<unknown>;
  query?: ZodType<unknown>;
  params?: ZodType<unknown>;
};

Core Function

const safeParse = <T>(schema: ZodType<T>, data: unknown): T => {
  const result = schema.safeParse(data);
  if (!result.success) throw result.error;
  return result.data;
};

Middleware

export const validationRequest = (schemas: ValidationSchemas) => {
  return (req: Request, _: Response, next: NextFunction): void => {
    try {
      if (schemas.body)
        req.body = safeParse(schemas.body, req.body) as typeof req.body;
      if (schemas.query)
        req.query = safeParse(schemas.query, req.query) as typeof req.query;
      if (schemas.params)
        req.params = safeParse(schemas.params, req.params) as typeof req.params;

      next();
    } catch (error) {
      if (error instanceof ZodError) {
        const firstIssue = error.issues[0];

        return next(
          new HTTPException(
            firstIssue.message,
            StatusCodes.UNPROCESSABLE_ENTITY,
          ),
        );
      }

      next(error);
    }
  };
};

Features

  • Multi-location validation: Validates body, query, and params simultaneously
  • Type-safe: Uses Zod schemas for runtime type validation
  • Automatic error handling: Converts Zod validation errors to HTTP exceptions
  • Early failure: Returns first validation error with 422 status code
  • Seamless integration: Overwrites request properties with parsed/validated data

Example Usage

import { validationRequest } from './middleware';
import { z } from 'zod';

// Define schemas
const userSchema = z.object({
  name: z.string().min(3),
  email: z.string().email(),
  age: z.number().min(18),
});

const querySchema = z.object({
  page: z.coerce.number().min(1).default(1),
  limit: z.coerce.number().min(1).max(100).default(10),
});

const paramsSchema = z.object({
  id: z.string().uuid(),
});

// Apply middleware to route
app.post(
  '/users/:id',
  validationRequest({
    body: userSchema,
    query: querySchema,
    params: paramsSchema,
  }),
  (req, res) => {
    // req.body, req.query, and req.params are now validated and typed
    const { name, email, age } = req.body;
    const { page, limit } = req.query;
    const { id } = req.params;

    res.json({ success: true });
  },
);

Error Response

When validation fails, the middleware returns:

{
  "statusCode": 422,
  "status": "fail",
  "message": "Invalid email address"
}

Key Benefits

  • Centralized validation logic: Keep validation separate from route handlers
  • Type inference: Zod schemas provide TypeScript type safety
  • Clean error handling: Consistent error format for all validation failures
  • Performance: Only validates specified request parts
  • Flexible: Can validate any combination of body, query, and params