skip to content

In Express 5, how do you write a reusable validation middleware that wraps a schema and keeps invalid input away from route handlers?

level: middleimportance: must knowfreq 65%

answer

  1. a factory returning (req, res, next)
  2. after the parser, before the handler
  3. return on failure, next() on success
  4. store the parsed copy once

basics

~20 s

Write a factory that takes a schema and returns (req, res, next) middleware: parse the input, stop with a 400 or next(err) on failure, store the parsed result and call next() on success, mounted after express.json and before the handler.

solid answer

~40 s

`validate(schemas)` returns an ordinary Express middleware. For each request part it runs the schema — `safeParse` in a schema library such as Zod — and on failure it either answers `res.status(400)` itself or calls `next(err)` with `err.status = 400` so the central error handler shapes the body; either way it `return`s, so it never also calls `next()`. On success it stores the parsed output once, for example on `req.valid.body`, and calls `next()`. It is mounted per route between the parser and the handler: `orders.post('/', validate({ body: createOrder }), create)`. Two Express 5 facts matter: `req.body` is `undefined` until a parser such as `express.json()` has run, and a rejected promise from an `async` middleware is forwarded to error handling, so an async schema needs no wrapper.

code

javascript · 35 lines
javascript
const express = require('express');
const { z } = require('zod');

const validate = (schemas) => async (req, res, next) => {
  const valid = {};
  for (const [part, schema] of Object.entries(schemas)) {
    const result = await schema.safeParseAsync(req[part]);
    if (!result.success) {
      const err = new Error(`Invalid request ${part}`);
      err.status = 400;
      err.issues = result.error.issues;
      return next(err);
    }
    valid[part] = result.data;
  }
  req.valid = valid;
  next();
};

const createOrder = z.object({ sku: z.string(), quantity: z.number().int().positive() });

const orders = express.Router();
orders.post('/', validate({ body: createOrder }), (req, res) => {
  const { sku, quantity } = req.valid.body;
  res.status(201).json({ sku, quantity });
});

const app = express();
app.use(express.json());
app.use('/v1/orders', orders);
app.use((err, req, res, next) => {
  res.status(err.status ?? 500).json({ error: err.message, issues: err.issues });
});

module.exports = app;

go deeper

for a junior

Recall that middleware has the signature (req, res, next), that a route can take several handlers in a row, and that the validator must either respond or call next().

for a middle

Explain the factory shape, why the validator goes after express.json(), how the parsed result reaches the handler, and the difference between responding with 400 and forwarding with next(err).

for a senior

Show the failure modes you have debugged: fall-through after a response, undefined bodies on the wrong media type, handlers reading raw input, and async schemas whose rejections must reach the error handler.

for a principal

Be ready to argue where the one validation factory lives, which property every service stores parsed input on, and whether failures are answered inline or always forwarded to a shared error handler.

## What the middleware is Express middleware is any function with the signature `(req, res, next)`. It may end the request by sending a response, or pass control on by calling `next()`; calling `next(err)` with anything other than the strings `'route'` or `'router'` skips the ordinary middleware and jumps to the **error-handling middleware**, the four-argument `(err, req, res, next)` functions registered later. A **validation middleware** is middleware whose only job is to check request input against a schema before the route handler sees it. Making it reusable means writing a **factory**: a function that takes the schema (or one schema per request part) and returns the middleware. ```js const validate = (schemas) => async (req, res, next) => { /* ... */ }; orders.post('/', validate({ body: createOrder }), createOrderHandler); ``` Express accepts any number of handlers on one route and runs them left to right, so the validator sits between the router's match and the handler. ## Where it is mounted The order matters, and Express runs layers in exactly the order they were registered: 1. A body parser, `express.json()`, registered on the app or the router. In Express 5, `req.body` is **`undefined`** until a parser has run (Express 4 initialised it to `{}`), and `express.json()` only parses requests whose `Content-Type` matches its `type` option, `application/json` by default. 2. The validator, on the route or on the resource router. 3. The handler, which reads only the parsed result. A validator mounted before the parser sees `undefined` for every body and fails every request — or, worse, a validator that skips "empty" bodies lets everything through. ## The success path: hand the handler the parsed copy A schema does more than say yes or no. It returns a **parsed value**: unknown keys stripped (depending on the schema), strings coerced to numbers, defaults filled in. The handler should read that value and never the raw input, so the middleware stores it once: - `req.body` is a plain property set by the parser, so `req.body = result.data` works, though it hides the fact that the value changed. - A property the middleware owns, such as `req.valid = { body, query, params }`, says plainly what it holds and works for every request part. - `req.query` is the exception: in Express 5 it is a **getter**, so assigning to it throws in strict code. Query validation must store its result somewhere else. Route parameters can be validated the same way, with one caveat: `req.params` is only filled in once a route has matched, so a validator for `params` has to be passed to the route itself — `orders.get('/:id', validate({ params: idParams }), getOrder)` — rather than mounted with `router.use()` ahead of it, where the route's `:id` has not been matched yet. ## The failure path: respond or forward | Approach | What the middleware does | Trade-off | |---|---|---| | Respond | `return res.status(400).json(...)` | self-contained, but every copy of the body format can drift | | Forward | `return next(err)` with `err.status = 400` | the error handler owns one body format for all errors | Either way, **`return`** matters. A middleware that sends the 400 and then falls through to `next()` lets the handler run; the handler's own `res.status(201).json(...)` then throws `ERR_HTTP_HEADERS_SENT` because the 400 already went out. What the failure body should contain, and whether 400 or 422 fits, belongs to REST error design; the middleware only decides how the failure reaches the response. ## Async schemas in Express 5 Some schemas need `await`: an async refinement that checks a database, for example, needs `safeParseAsync`. Express 5's router forwards a **rejected promise returned by middleware** to error handling, exactly as if it had been passed to `next(err)`, and it does the same for an exception thrown synchronously. So an `async` validator needs no try/catch wrapper. In Express 4 the rejection was never forwarded: it surfaced as an unhandled rejection, which on current Node.js versions terminates the process by default, and the request never got its error response. ## Mistakes to look for - Falling through to `next()` after responding. - Validating before `express.json()`, or on a route whose requests use another media type. - Handlers reading `req.body` or `req.query` after validation instead of the parsed copy. - Assigning the parsed query back to `req.query`. - One validator per route written by hand, so each one shapes failures differently. Kept small — parse, store, forward — the middleware is the single place where untrusted input becomes trusted input for the rest of the route.

  • Why forward with next(err) instead of answering 400 inside the validation middleware?
    Forwarding puts every failure body in one function, the error handler registered last, so validation failures look like every other error and a format change touches one place. Answering inline is simpler and keeps the middleware self-contained, but each copy can drift. Either way the middleware must `return` on the failure path so it never also calls `next()`.
  • What happens if the route validates a JSON body but the client sends text/plain?
    `express.json()` only parses requests whose `Content-Type` matches its `type` option, `application/json` by default, so it skips the body and in Express 5 `req.body` stays `undefined`. The schema then fails on `undefined`, which is the right outcome. A validator that skips validation when `req.body` is missing would let the request through unchecked.

  • Calling next() after sending the 400, so the route handler runs as well.
  • Validating req.body on a route where express.json() has not run yet.
  • Letting the handler read req.body again instead of the parsed result.
  • Believing Express 5 needs a wrapper to forward an async middleware's rejection.
  • Skipping validation when req.body is undefined, as if the request were empty.

Assumes Express 5: req.body is undefined until a parser runs (Express 4 gave {}), and a rejected promise from async middleware reaches error handling without a wrapper.