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.
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.
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();
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With