Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express V5: Is there any way to modify `req.query`?

Express v5 changed the behavior of req.query:

The req.query property is no longer a writable property and is instead a getter.

That being the case... In our ExpressV4 app, we use Joi in middleware for validation on the request {body,query,params}. Among other things Joi can be used to e.g. set a default value if it was blank, or coerce ?inStock=1 to params: {inStock: true}. I'm migrating to v5 and this is the last hurdle that's blocking me.

It appears that req.body is still mutable in this way but this is no longer the case for req.query in v5. So... Is there any creative way to manipulate req.query in a middleware?

If not, I'll be stuck with adding a new property like req.validatedQuery = validate(schema, req.query) and I'll have to change all of my request handlers to use req.validatedQuery which is less than ideal.

Update

I am trying to make sense of why it's acceptable for body, params, headers to be mutable but not query. The purpose of middleware is to modify the request or response. query is already a parsed interpretation of the raw URL, and it can be changed if you change the parser.

Validation happens at a different stage of the middleware pipeline but I don't see any justification for why it shouldn't be acceptable to coerce/sanitize/normalize the query the same as body before it reaches your route handler.

like image 346
thom_nic Avatar asked Oct 31 '25 14:10

thom_nic


1 Answers

Add this to make it writable:

app.use((req, res, next) => {
    Object.defineProperty(req, 'query', { ...Object.getOwnPropertyDescriptor(req, 'query'), value: req.query, writable: true });
    next();
});
like image 83
zecat Avatar answered Nov 03 '25 05:11

zecat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!