Skip to content
jshacks.dev
APIs

Add request validation middleware

Add request validation middleware to Express with a Zod schema, so handlers receive a checked body or the client gets a 400.

1 min read
Summarize in AI

A middleware that validates the body keeps the check out of each handler. The route receives a parsed object, or never runs.

validate.jsJavaScript
import express from 'express';
import { z } from 'zod';

const validate = (schema) => (req, res, next) => {
  const result = schema.safeParse(req.body);
  if (!result.success) {
    return res.status(400).json({ errors: result.error.issues.map((i) => i.path.join('.')) });
  }
  req.body = result.data;
  next();
};

const app = express();
app.use(express.json());

app.post('/users', validate(z.object({ name: z.string().min(1) })), (req, res) => {
  res.status(201).json({ name: req.body.name });
});

const server = app.listen(0, async () => {
  const url = `http://localhost:${server.address().port}/users`;
  const send = (body) =>
    fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });

  for (const body of [{ name: 'Ada' }, { name: '' }]) {
    const res = await send(body);
    console.log(res.status, await res.json());
  }
  server.close();
});
Text
201 { name: 'Ada' }
400 { errors: [ 'name' ] }

validate(schema) returns the middleware, so each route names its own schema. Replacing req.body with result.data means the handler sees the parsed value, with unknown keys removed and defaults applied.

The same factory can check req.query or req.params. Return a stable error format rather than the raw Zod issues if clients depend on it. Express 5 is assumed; express.json() must run first or req.body is undefined.

Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
APIs

Accept multipart upload in Node.js

Accept a multipart file upload in Node.js by wrapping the incoming request in a Request object and reading it with formData.

1 min read
Performance

Reduce JSON size by removing nulls

Drop null and undefined fields from an API payload with a JSON.stringify replacer, shrinking responses, and check clients treat a missing key like null.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.