Zod Express Middleware

1.4.0 · maintenance · verified Wed Apr 22

`zod-express-middleware` is an Express.js middleware library designed to enforce type safety and validate incoming request data (body, query, and parameters) using Zod schemas. Currently at version 1.4.0, it provides functions like `validateRequest` to check if an incoming request conforms to predefined Zod schemas without modifying the request object. For scenarios requiring data transformation or stripping unknown keys, it offers `processRequest` and its specific variants (`processRequestBody`, `processRequestQuery`, `processRequestParams`), which leverage Zod's `.transform` and `.refine` methods. The package maintains a steady release cadence, integrating smoothly with `express` and `zod` as peer dependencies. Its primary differentiator is the direct integration of Zod's powerful, inferential schema validation capabilities into the Express middleware pipeline, providing a robust solution for ensuring API contract adherence and improving developer experience through strong typing.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up an Express application with `zod-express-middleware` to validate `req.params`, `req.body`, and `req.query` using Zod schemas for a POST endpoint. It includes basic Express setup, JSON body parsing, and a global error handler for Zod validation failures.

import express from 'express';
import { validateRequest } from 'zod-express-middleware';
import { z } from 'zod';

// Create an express app
const app = express();

// Add express.json() middleware to parse JSON bodies
app.use(express.json());

// Define an endpoint using express, zod and zod-express-middleware
app.post("/:urlParameter/", validateRequest({
    params: z.object({
      urlParameter: z.string().uuid("Invalid URL parameter format"),
    }),
    body: z.object({
      bodyKey: z.number().int().positive("bodyKey must be a positive integer"),
      optionalField: z.string().optional()
    }),
    query: z.object({
      queryKey: z.string().length(64, "queryKey must be 64 characters long"),
    }),
  }), (req, res) => {
    // req.params, req.body and req.query are now strictly-typed and confirm to the zod schema's above.
    // req.params has type { urlParameter: string };
    // req.body has type { bodyKey: number; optionalField?: string };
    // req.query has type { queryKey: string };
    console.log('Validated Params:', req.params);
    console.log('Validated Body:', req.body);
    console.log('Validated Query:', req.query);
    return res.json({message: "Validation for params, body and query passed", data: { params: req.params, body: req.body, query: req.query }});  
  }
);

app.get('/', (req, res) => {
  res.send('Welcome to the Zod Express Middleware example!');
});

// Error handling middleware for ZodErrors
app.use((err, req, res, next) => {
  if (err instanceof z.ZodError) {
    return res.status(400).json({
      status: 'error',
      message: 'Validation failed.',
      errors: err.errors.map(e => ({ path: e.path.join('.'), message: e.message }))
    });
  }
  next(err);
});

// Start the express app on port 8080
const PORT = process.env.PORT ?? 8080;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log('Try POST to /<uuid-param>?queryKey=... (64 chars) with JSON body { "bodyKey": 123 }');
});

view raw JSON →