0

Can the req object be manipulated within a HTTP request? So is there any chance a request can set a value for req.token? I know that various object properties like req.query, req.body etc. can be freely changed from the outside, but can new properties like req.token be added or is this example code safe?

var auth = function (req, res, next) {
    if (isValid()) {
        req.token = getToken();
        return next();
    }
}

app.get('/foo', auth, function(req, res) {
    if (req.token) {
        // valid request
    } else {
        // invalid request
    }
});
Chris
  • 4,255
  • 7
  • 42
  • 83
  • 1
    Yes, you can do this, although the recommended way is to use req.locals. see http://stackoverflow.com/questions/33451053/req-locals-vs-res-locals-vs-res-data-vs-req-data-vs-app-locals-in-express-mi – Patrick Hund May 05 '17 at 08:06
  • 1
    Possible duplicate of [req.locals vs. res.locals vs. res.data vs. req.data vs. app.locals in Express middleware](http://stackoverflow.com/questions/33451053/req-locals-vs-res-locals-vs-res-data-vs-req-data-vs-app-locals-in-express-mi) – Patrick Hund May 05 '17 at 08:06

1 Answers1

1

Yes, it's safe, provided you don't overwrite a property that a special meaning (a non-exhaustive list of those can be found here).

It's a commonly used technique, and it's also shown in the Express documentation.

robertklep
  • 198,204
  • 35
  • 394
  • 381