11

Is it possible to write a middleware which executes after the response is sent to a client or after the request is processed and called just before sending the response to client?

Chenmunka
  • 685
  • 4
  • 21
  • 25
Selvaraj M A
  • 3,096
  • 3
  • 30
  • 46

2 Answers2

15

pauljz gave the basic method but to expand on that here is an example of middleware

module.exports = function() {
  return function(req, res, next) {
    req.on("end", function() {
      // some code to be executed after another middleware
      // does some stuff
    });
    next(); // move onto next middleware
  }
}

In your main app

expressApp.use(require("./doneMiddleware"));
expressApp.use(express.logger());
expressApp.use(express.static.....
Morgan ARR Allen
  • 10,556
  • 3
  • 35
  • 33
  • If I understand correctly, this event will trigger when the client completes sending request/data to server. But what I want is, after calling response.render or response.redirect etc, the middle ware should be executed. – Selvaraj M A Jul 21 '13 at 11:41
  • 1
    No, this event is emitted once the entire request is done, including sending the response. So long as render/redirect call response.end the associated request will emit end. – Morgan ARR Allen Jul 22 '13 at 16:31
  • 1
    @SelvarajMA The following approach may be better: http://stackoverflow.com/a/21858212/673014. – pronskiy Mar 09 '17 at 13:03
4

See if binding to req.on('end', function() {...}); will work for you.

pauljz
  • 10,803
  • 4
  • 28
  • 33
  • If I understand correctly, this event will trigger when the client completes sending request/data to server. But what I want is, after calling response.render or response.redirect etc, the middle ware should be executed. – Selvaraj M A Jul 21 '13 at 11:41