chebad
chebad

Reputation: 1017

Modify response body before res.send() executes in ExpressJS

In application which I currently develop, it's using Express. In my case I want to get response before it's been sent and modify it (for purpose of JWT). In this application, there is a dozen of endpoints and I don't want to create my own function like sendAndSign() and replace res.send() everywhere in code. I heard there is option to override/modify logic of res.send(...) method.

I found something like this example of modifying, but in my case this doesn't work. Is there any other option (maybe using some plugin) to manage this action?

Upvotes: 6

Views: 11374

Answers (2)

Arik
Arik

Reputation: 6501

I have created an NPM package called experss-response-hooks that provides response hooks.

You can register a hook in a middleware before all your other routes, that will enable you to change the response body when send() will be called.

For example:

const responseHooks = require('express-response-hooks');

// response hooks initialization
app.use(responseHooks());

// register a middleware that modifies the response body before being sent to the client
app.use(function (req, res, next) {
  // hook on "send()" function
  res.hooks.on('send', (args) => {
    args[0] = 'new-body'; // args[0] is the body passed to send()
  });
});

Upvotes: 0

shaochuancs
shaochuancs

Reputation: 16226

You can intercept response body in Express by temporary override res.send:

function convertData(originalData) {
  // ...
  // return something new
}

function responseInterceptor(req, res, next) {
  var originalSend = res.send;

  res.send = function(){
    arguments[0] = convertData(arguments[0]);
    originalSend.apply(res, arguments);
  };
  next();
}

app.use(responseInterceptor);

I tested in Node.js v10.15.3 and it works well.

Upvotes: 23

Related Questions