skip to content

After an Express 5 upgrade, a validation middleware running req.query = schema.parse(req.query) throws a TypeError; where should the validated query live, and what must its schema expect?

level: seniorimportance: should knowfreq 40%

answer

  1. req.query stays the raw parse
  2. a property the middleware owns
  3. coerce strings, normalise arrays
  4. audit Express 4 middleware

basics

~20 s

Leave req.query as the raw parse, since Express 5 made it read-only, and have the middleware write the validated result to a property it owns, such as req.valid.query, with a schema that coerces the strings the query string arrives as.

solid answer

~50 s

In Express 5 `req.query` is a read-only view of the URL, so it cannot hold a validated copy; why the assignment throws belongs with the request object itself. The REST fix is to give the result its own home: the middleware runs the schema with `safeParse`, forwards a 400 on failure, and on success writes `req.valid = { ...req.valid, query: result.data }`; handlers read only `req.valid.query`. That property is an ordinary own property, scoped to one request, and its name says the value has been checked. `res.locals` is the view engines' object and `app.locals` is shared by every request, so neither is a good home. The schema must match what the default parser hands it: every value is a string, so numbers need coercion (`z.coerce.number()`), and a key is a string when sent once but an array when repeated, so list fields must accept both and normalise.

code

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

// Express 4 habit: breaks in Express 5
const validateQueryOld = (schema) => (req, res, next) => {
  req.query = schema.parse(req.query); // TypeError in strict code, ignored in sloppy code
  next();
};

// Express 5: store the parsed copy on a property the middleware owns
const validateQuery = (schema) => (req, res, next) => {
  const result = schema.safeParse(req.query);
  if (!result.success) {
    const err = new Error('Invalid query');
    err.status = 400;
    return next(err);
  }
  req.valid = { ...req.valid, query: result.data };
  next();
};

const listQuery = z.object({ page: z.coerce.number().int().min(1).default(1) });

const app = express();
app.get('/v1/orders', validateQuery(listQuery), (req, res) => {
  res.json({ page: req.valid.query.page }); // a number, with the default applied
});

module.exports = { app, validateQueryOld };

go deeper

for a junior

Remember that in Express 5 req.query is read-only: you read the parsed query from it, but a validated or coerced copy goes on a different property.

for a middle

Write the validation middleware so it stores its result on an owned property, and a schema that coerces query strings and normalises single values to arrays.

for a senior

Diagnose the upgrade from symptoms, a TypeError naming query in logs or handlers silently receiving strings, then fix every assignment, including third-party middleware, and every handler still reading the raw query.

for a principal

Decide one house property for validated input across services, make the validation middleware its only writer, and audit the codebase for Express 4 query patterns during the migration.

## The one Express fact In Express 5, `req.query` is a read-only view of the URL's query string rather than a slot for application data, so `req.query = schema.parse(req.query)` cannot work; the request-object material covers why it throws in strict code and silently does nothing in sloppy code. For REST wiring the consequence is simple: **the validated query needs a home of its own**, and every handler must read it from there. ## Choosing the home | Option | Verdict | Why | |---|---|---| | `req.valid.query`, a property the middleware owns | use it | an ordinary own property, so assignment works; scoped to one request; the name says the value is validated | | `res.locals.query` | avoid | request-scoped too, but Express documents it as the object view engines read and warns against user-controlled keys there | | `Object.defineProperty(req, 'query', ...)` | avoid | it works, but other code expects `req.query` to be the raw parse, and it leans on how Express happens to define the getter | | `app.locals` or a module variable | never | shared by every concurrent request, so one request overwrites another's values | Merge rather than overwrite (`req.valid = { ...req.valid, query: result.data }`), so a route that validates the body and the query in two steps keeps both. In TypeScript, add `valid` to the `Request` type once, through declaration merging, so handlers get the parsed types instead of `any`. ## What the schema must expect Validation has to match what the default `simple` parser produces, not what the API documentation promises: 1. **Every value is a string.** `?page=2` gives `'2'`, so a schema field declared as a plain number rejects it. Use coercion (`z.coerce.number().int().min(1)` in Zod) and give optional fields their defaults in the schema, so the handler never repeats them. 2. **A key is a string once and an array when repeated.** `?tag=a` gives `'a'` while `?tag=a&tag=b` gives `['a', 'b']`. A list field must accept both and normalise to an array, or the single-value request fails validation. 3. **Unknown keys are input too.** Decide per endpoint whether the schema strips them or rejects them, and let the validated object carry only the keys the API defines. 4. **An empty value is a string too.** `?page=` gives `''`, and `z.coerce.number()` turns `''` into `0`, so keep the range and integer checks (`.int().min(1)`) after the coercion rather than trusting it alone. ## Auditing a migrated codebase - Search for `req.query =` and for `req.query.` on the left of an assignment: every hit must become a write to the owned property. - Search handlers for reads of `req.query` on validated routes: after the change they must read `req.valid.query`, or they quietly get the uncoerced strings back. - Check third-party middleware written for Express 4 that sanitises or rewrites the query object in place; it has the same problem and may fail silently rather than throw. - Run the test suite from ES modules or `'use strict'` files, so a leftover assignment fails loudly instead of being ignored. ## The house rule Pick one property name for validated input across services (`req.valid` with `body`, `query` and `params`), make the validation middleware the only writer, and treat `req.query`, `req.body` and `req.params` as raw input that handlers on validated routes never read. A reviewer can then check one rule instead of auditing every handler.

  • Could you redefine req.query with Object.defineProperty instead?
    It works: Express defines the getter as configurable on its request prototype, so an own property on the request object shadows it. It is still a workaround. Other middleware and logging expect `req.query` to be the raw parse, and the code leans on how Express happens to define the getter rather than on documented API. A separate property says what it holds.
  • A list filter accepts ?tag=a&tag=b; why does ?tag=a fail validation, and how should the schema handle it?
    Under Express 5's default parser a key sent once arrives as a string and a repeated key as an array of strings, so a schema that declares `tag` as an array rejects the single value. Accept both and normalise: in Zod, `z.union([z.string(), z.array(z.string())]).transform((v) => (Array.isArray(v) ? v : [v]))`. The handler then always receives an array, whichever form the client sent.

  • Assigning the parsed result back to req.query, as Express 4 code did.
  • Declaring query fields as plain numbers in the schema without coercion.
  • Assuming a key sent once arrives as a one-element array.
  • Handlers on validated routes still reading req.query instead of the validated copy.
  • Storing per-request validated input on app.locals, which every request shares.

Assumes Express 5: req.query is read-only and its default parser yields strings and arrays of strings; in Express 4 middleware could overwrite it.