node express accessing req

I’m trying to redefine send and pass an express-session value with every response. However, I can’t access req inside the definition of send.

01| let app = express();
02| app.use(bodyParser.json());
03| app.use(bodyParser.urlencoded({ extended: true }));
...
56| app.use(function(req, res, next) {
57|   const _send = res.send;
58|   res.send = (props) => {
59|     return _send({ props, authenticated: !!req.session?.authenticated });
60|   };
61|   next();
62| });
63|
64| app.get("/debug/users", async (req, res) => {
65|   const users = await models.User.getAllRows();
66|   return res.send(`<pre>${JSON.stringify(users, null, 2)}</pre>`);
67| });

I get the following error:

TypeError: Cannot read property 'req' of undefined
    at send (/server/node_modules/express/lib/response.js:110:18)
    at ServerResponse.res.send (/server/src/index_session_auth.js:59:12)
    at /server/src/index_session_auth.js:66:14
    at processTicksAndRejections (node:internal/process/task_queues:94:5)

How do I fix this so that I can use req inside the redefinition of send()?

Answer

Look at the send method you are overriding:

res.send = function send(body) {
  var chunk = body;
  var encoding;
  var req = this.req;

It cares about the value of this which you are changing by calling _send() instead of res.send().

You need to maintain the this value.

return _send.call(res, { props, authenticated: !!req.session?.authenticated });