| | |

Zod 28 🛡️ Express Integration — Request validation middleware

⏱️ Estimated read: 10 min | |

Express hands the route handler whatever the client sent. req.body is whatever JSON was parsed, req.query is a string-keyed object, and req.params is the URL segments. A TypeScript annotation on the handler does not change the runtime value, and a missing field becomes undefined at the point of use. Zod’s role in Express is to be the gate: a middleware parses the relevant parts of the request against a schema, replaces the raw values with the parsed output, and returns a 400 before the handler runs.

This chapter covers the middleware pattern, the three request locations that need validation, and the error-handling integration that turns a ZodError into a structured response. The sections that follow walk through the hand-written middleware, the schema design for body/query/params, and the centralized error handler that keeps validation failures consistent across routes.

Key point: A Zod validation middleware calls schema.parse(req.body) (or req.query/req.params), assigns the parsed result back to the request property, and catches ZodError to return a 400; query and params need z.coerce because their values are always strings.


a. The hand-written validation middleware

The core pattern is a higher-order function that takes a schema and returns an Express middleware. The middleware parses the request property, overwrites it with the parsed output, and calls next(). If the parse throws a ZodError, the middleware returns a 400 with the issues.

import { z } from "zod";
import { Request, Response, NextFunction } from "express";

function validateBody<T extends z.ZodTypeAny>(schema: T) {
  return (req: Request, res: Response, next: NextFunction) => {
    try {
      req.body = schema.parse(req.body); // overwrite with parsed output
      next();
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({
          error: "Validation failed",
          details: error.issues,
        });
      }
      next(error);
    }
  };
}

The assignment req.body = schema.parse(req.body) is the part that makes the handler type-safe. The schema’s output type is what the handler receives, which means a .transform() or .default() is applied before the handler reads the field. Without the assignment, the handler would read the raw value and the schema’s coercion would be lost .

The same pattern applies to req.query and req.params. A combined middleware validates all three locations in one call, which is the pattern that express-zod-guard and similar packages provide .

function validateRequest(schemas: {
  body?: z.ZodTypeAny;
  query?: z.ZodTypeAny;
  params?: z.ZodTypeAny;
}) {
  return (req: Request, res: Response, next: NextFunction) => {
    try {
      if (schemas.body) req.body = schemas.body.parse(req.body);
      if (schemas.query) req.query = schemas.query.parse(req.query);
      if (schemas.params) req.params = schemas.params.parse(req.params);
      next();
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ details: error.issues });
      }
      next(error);
    }
  };
}

The express-zod-guard package implements this pattern with a 422 status code and a flatter error shape, and it validates only the locations that are specified in the options object . The choice between the package and the hand-written version is the same trade-off as any small dependency: the package saves the boilerplate, the hand-written version has no dependency risk.


b. Schema design for query and params

The schema for req.body is the schema the application would use anywhere else—it validates the JSON that express.json() produced. The schemas for req.query and req.params are different because Express produces them as strings, and Zod’s numeric and boolean validators reject strings.

req.query in Express 5 is a getter that returns a parsed object, and its values are strings or arrays of strings. A page query parameter is "1", not 1. The schema must coerce it:

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

req.params has the same constraint. A route parameter that should be a number needs z.coerce.number(), and a route parameter that should be a UUID uses z.uuid() (or z.string().uuid() in v3 syntax).

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

The z.coerce is not optional for these locations. A schema that uses z.number() on req.query.page rejects every request with a type error, because the value is always a string . The coercion is the bridge between Express’s string representation and the schema’s expected type.

The error handler should distinguish the locations in the response. A details array with the path from each issue is enough for the client to map the error to the field, and the path for a query issue starts with the parameter name.


c. The centralized error handler

A per-route try/catch works for a small application, but a larger one centralizes the ZodError handling in an Express error middleware. The middleware checks error instanceof z.ZodError (or isZodErrorLike from zod-validation-error) and returns a 400 with the issues; any other error passes to the next error handler .

import { ErrorRequestHandler } from "express";
import { z } from "zod";

const handleValidationError: ErrorRequestHandler = (err, req, res, next) => {
  if (!(err instanceof z.ZodError)) {
    return next(err); // not a validation error; pass to the next handler
  }
  res.status(400).json({
    error: "Validation failed",
    issues: err.issues,
  });
};

app.use(handleValidationError);

The centralized handler requires the route-level middleware to call next(error) instead of returning the response itself. The pattern is to have the validation middleware parse and assign the values, and to let the parse error propagate to the central handler. The express-zod-guard package takes the opposite approach—it returns the 422 from the middleware—which means the central handler never sees the validation error . Both work; the choice is whether the validation error format is defined in one place or per route.

The zod-validation-error package formats a ZodError into a human-readable string and provides an isZodErrorLike guard that works across Zod versions . The fromError() function returns an object with a message and a details array, which is convenient for a response body that needs a readable summary alongside the structured issues.


Complete Example Session

// ============================================
// PART 1: THE SCHEMAS
// ============================================
import { z } from "zod";

const createUserSchema = z.object({
  username: z.string().min(3).max(20),
  email: z.email(),
  password: z.string().min(8),
  age: z.number().int().positive().optional(),
});

const searchQuerySchema = z.object({
  q: z.string().optional(),
  page: z.coerce.number().int().min(1).default(1),
  limit: z.coerce.number().int().min(1).max(100).default(10),
});

const userParamsSchema = z.object({
  userId: z.uuid(),
});

// ============================================
// PART 2: THE COMBINED MIDDLEWARE
// ============================================
import { Request, Response, NextFunction } from "express";

function validateRequest(schemas: {
  body?: z.ZodTypeAny;
  query?: z.ZodTypeAny;
  params?: z.ZodTypeAny;
}) {
  return (req: Request, res: Response, next: NextFunction) => {
    try {
      if (schemas.body) req.body = schemas.body.parse(req.body);
      if (schemas.query) req.query = schemas.query.parse(req.query);
      if (schemas.params) req.params = schemas.params.parse(req.params);
      next();
    } catch (error) {
      next(error); // central handler formats the ZodError
    }
  };
}

// ============================================
// PART 3: THE CENTRAL ERROR HANDLER
// ============================================
import { ErrorRequestHandler } from "express";

const handleValidationError: ErrorRequestHandler = (err, req, res, next) => {
  if (!(err instanceof z.ZodError)) return next(err);
  res.status(400).json({
    error: "VALIDATION_ERROR",
    issues: err.issues.map((i) => ({
      path: i.path.join("."),
      message: i.message,
    })),
  });
};

app.use(handleValidationError);

// ============================================
// PART 4: THE ROUTES
// ============================================
app.post(
  "/users",
  validateRequest({ body: createUserSchema }),
  (req: Request, res: Response) => {
    const { username, email } = req.body; // typed and validated
    res.status(201).json({ username, email });
  }
);

app.get(
  "/search",
  validateRequest({ query: searchQuerySchema }),
  (req: Request, res: Response) => {
    const { q, page, limit } = req.query; // numbers, with defaults
    res.json({ q, page, limit });
  }
);

app.get(
  "/users/:userId",
  validateRequest({ params: userParamsSchema }),
  (req: Request, res: Response) => {
    const { userId } = req.params; // validated UUID
    res.json({ userId });
  }
);

The parts covered the schemas for body, query, and params, the combined middleware, the centralized error handler, and the routes that receive the parsed values.


Quick Reference

Validation Middleware Pattern

StepCode
Parse bodyreq.body = schema.parse(req.body)
Parse queryreq.query = schema.parse(req.query)
Parse paramsreq.params = schema.parse(req.params)
Errorcatch → next(error)
Central handlererr instanceof z.ZodError → 400

Location Constraints

LocationValue TypeSchema Pattern
req.bodyJSON typesz.object({ ... })
req.queryStringsz.coerce.number()
req.paramsStringsz.coerce.number() or z.uuid()

Middleware Packages

PackageStatusNotes
express-zod-guardActive422, multi-location
@luolapeikko/zod-express-middlewareActiveReplacement for zod-express-middleware
zod-express-validatorActiveIncludes response validation
express-zod-apiActiveFull framework, not just middleware

Best Practices

✅ Do This:

// Overwrite the request property with the parsed value
req.body = schema.parse(req.body);                            // ✅

// Use coerce for query and params
page: z.coerce.number().int().min(1)                          // ✅

// Centralize the ZodError handler
app.use(handleValidationError);                               // ✅

❌ Don’t Do This:

// Use z.number() on a query parameter
page: z.number() // rejects every string                         // ❌

// Parse without assigning
schema.parse(req.body); // handler still sees raw data          // ❌

// Return 500 on a validation error
// (validation failure is a client error, not a server error)  // ❌

Common Pitfalls

PitfallWhy It HappensFix
Query validation always failsz.number() usedz.coerce.number()
Handler sees undefinedParse result not assignedAssign back to req.body
Validation error returns 500No ZodError handlerAdd central error middleware
Params not validatedNo params schemaAdd params to the middleware

Real-World Examples

1. Body validation

req.body = createUserSchema.parse(req.body);

2. Query coercion

page: z.coerce.number().default(1)

3. UUID param

userId: z.uuid()

4. Central handler

if (err instanceof z.ZodError) return res.status(400).json({ issues: err.issues });

5. Combined middleware

validateRequest({ body: userSchema, params: idSchema })

6. Optional body field

age: z.number().int().positive().optional()

7. zod-validation-error

import { fromError } from "zod-validation-error";

8. express-zod-guard

validationRequest({ body: userSchema })

9. Route with validation

app.post("/users", validateRequest({ body: userSchema }), handler);

10. Issue path mapping

issue.path.join(".")

Visual

The Middleware Flow

┌─────────────────────────────────────────────────────────┐
│  Request arrives                                        │
│         │                                               │
│         ▼                                               │
│  validateRequest({ body: Schema })                      │
│         │                                               │
│         ▼                                               │
│  Schema.parse(req.body)                                 │
│         │                                               │
│    ┌────┴────┐                                          │
│    ▼         ▼                                          │
│  valid     invalid                                      │
│    │         │                                          │
│    ▼         ▼                                          │
│  req.body  next(ZodError)                               │
│  = parsed      │                                        │
│    │           ▼                                        │
│    ▼      Central handler → 400                         │
│  next()                                                 │
│    │                                                    │
│    ▼                                                    │
│  Route handler reads validated data                     │
└─────────────────────────────────────────────────────────┘

Query String Coercion

┌─────────────────────────────────────────────────────────┐
│  URL: /search?page=2                                    │
│         │                                               │
│         ▼                                               │
│  req.query = { page: "2" }  (string)                    │
│         │                                               │
│         ▼                                               │
│  z.coerce.number().parse("2")                           │
│         │                                               │
│         ▼                                               │
│  req.query.page = 2  (number)                           │
└─────────────────────────────────────────────────────────┘

Error Handler Placement

┌─────────────────────────────────────────────────────────┐
│  app.use(express.json())                                │
│  app.use(routes)                                        │
│  app.use(handleValidationError)  ◄── after routes       │
│  app.use(genericErrorHandler)                           │
│                                                         │
│  Express calls error middleware in order.               │
│  The Zod handler must be before the generic one.        │
└─────────────────────────────────────────────────────────┘

Summary

ItemValue
Body validationschema.parse(req.body) and assign back
Query validationz.coerce required (values are strings)
Params validationz.coerce or format validators
Error handlingerr instanceof z.ZodError → 400
Central handlerErrorRequestHandler after routes
Package optionexpress-zod-guard, @luolapeikko/zod-express-middleware

Key takeaways:

  • The middleware parses and assigns. The req.body = schema.parse(req.body) line is what makes the handler receive the schema’s output type, including coercions and defaults. Without the assignment, the handler reads the raw value .
  • Query and params need coercion. Express produces both as strings, so z.coerce.number() is the correct schema for a numeric parameter. A plain z.number() rejects every request .
  • The central error handler keeps the format consistent. A single ErrorRequestHandler that checks err instanceof z.ZodError and returns a 400 with the issues means every route’s validation failure has the same shape .
  • The package choice is a dependency decision. express-zod-guard and @luolapeikko/zod-express-middleware provide the middleware pattern with different error shapes and status codes; the hand-written version is four lines and has no dependency risk .
  • Validation is not authorization. A schema that validates the body’s shape does not check whether the caller may perform the action. The handler still needs its own authorization checks after the middleware runs.

Remember: Express gives the handler whatever the client sent. The Zod middleware is the gate that turns that raw input into a typed, validated value before the handler reads a single field. Parse the body, query, and params; assign the parsed output back to the request; and let the central error handler format the failure. Use z.coerce for the locations that Express produces as strings, and keep the validation error separate from the 500 branch.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!