3

I am writing an Express application that I'm linting using the AirBnB eslint configuration. That lint configuration provides a no-params-reassign check, which flags reassignment of parameters and members of those parameters as errors. I personally like this, but I am unsure if there's a way to modify req and res in Express without mutating the function parameters.

For example, I want to rewrite part of the request in a middleware:

app.use((req, res, next) => {
  req.url = req.url.replace("regex", "replacement");
});

This sets off a lint error. I know I can make the error go away by doing this:

app.use((_req, res, next) => {
  req = _req;
  req.url = req.url.replace("regex", "replacement");
});

... but that seems like a kinda dumb solution. Is there a means of replacing the req and res variables for future middleware invocations in Express, or is the only way to persist changes to actually mutate them?

I know I can just override the no-params-reassign rule, but I wanted to see if it's possible for me to achieve this without doing so. Thanks!

osdiab
  • 1,972
  • 3
  • 26
  • 37
  • 2
    Short answer? Yeah, the general rule is to mutate `req` and `res` as they go by your middleware. The official guide even suggests [doing it that way](http://expressjs.com/en/guide/writing-middleware.html). There may be a way around it, but I've never seen one. Does `req.replacedUrl = req.url.replace("regex", "replacement");` make an `eslint` warning? – dvlsg Apr 20 '16 at 23:36
  • 1
    Yeah—the dogma is to not mutate the parameters. Guess Express may be incompatible with that? – osdiab Apr 21 '16 at 00:04
  • 1
    I could definitely be mistaken, but it seems to be the recommended way to do it with Express. And most nodejs http / server libraries, truth be told. I think the idea is that middleware is typically used to "extend" the request / response objects with the pieces you need. For better or worse. – dvlsg Apr 21 '16 at 16:40

1 Answers1

0

Is there a means of replacing the req and res variables for future middleware invocations in Express:

Use the app object as persistent storage at the first invocation, then check it on subsequent invocations

app.use( (req, res, next) => { 
  app.req = app.req || req;
  app.req.url = app.req.url.replace("regex", "replacement");
});

JSON.stringify and JSON.parse can be used to avoid mutation:

app.use( (req, res, next) => { 
  app.req = app.req || JSON.parse(JSON.stringify(req));
  app.req.url = app.req.url.replace("regex", "replacement");
});

References

Community
  • 1
  • 1
Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265