-3

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?

1
  • Welcome to Stack Overflow! I'd recommend editing your post to only include the problem you faced, then posting your solution as an answer to your own question. That way, the question is objective ("how do I fix this issue" rather than "what is the best practice"), and other folks can contribute alternative answers that might be more suitable. Then the best answer can be voted up, exactly how SO was built to work. Commented Oct 10 at 19:26

1 Answer 1

0

So I know these don't really answer your question, but just to have them said:

  1. The "official answer" is that you're not supposed to mutate req.query. It's immutable on purpose for various reasons. That's why it requires "a hack" to do it.

  2. That express-mongo-sanitize library has been abandoned for several years. I recommend you use caution if choosing it.

  3. The "official right answer" for something like this is to either write your new data to a different req property meant for internal use or to change req.url directly. The maintainer of the sanitize lib has no intention of ever supporting that (see previous bullet).

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your answer. I will look for an alternative library to express-mongo-sanitize that I can customize it to use the new req property I define instead of req.query. If you have any recommendation I would appreciate it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.