I'm using Express 5, and I'm now running into this error when using express-mongo-sanitize or xss-clean:
TypeError: Cannot set property query of #<IncomingMessage> which has only a getter
In Express 5, req.query is now defined as a getter instead of a plain object, which makes it immutable.
However, express-mongo-sanitize (and some other sanitization middlewares) attempt to mutate req.query in order to sanitize it — which causes this error.
My setup looks like this:
app.use(express.json());
app.use(mongoSanitize());
This used to work fine in Express 4, but not any more.
I found that redefining the req.query property before these sanitization middlewares works:
app.use((req, res, next) => {
Object.defineProperty(req, 'query', {
value: { ...req.query },
writable: true,
configurable: true,
enumerable: true,
});
next();
});
This makes req.query mutable again, and the sanitizers can modify it.
Is there a better or more "official" solution to this in Express 5 or just stick to this solution?