1

I want to save the amount of 4XX and 5XX errors served by my server. The approach that I took was to create an express middleware to get the statusCode response

const fooMiddleware = (req, res, next) => {
  req.stats.totalRequestsServed += 1;

  // I want to access the status code sent to the client here
  console.log('status code', res.statusCode);
  next(null);
};

I'm using the code above but I'm always getting a 200 status code, even If I hardcode a res.status(401).end() on my route.

Nicolas Del Valle
  • 1,384
  • 15
  • 20

3 Answers3

1

Your answer can be found here

app.use(function (req, res, next) {
    function afterResponse() {
        res.removeListener('finish', afterResponse);
        res.removeListener('close', afterResponse);

        // do smth after res.send
        console.log(res.status);
    }

    res.on('finish', afterResponse);
    res.on('close', afterResponse);

    // do smth before request eventually calling `next()`
    next();
});

Imho, hook is not transparency. It's need for some "special" cases.
Error handler is more better for logging 4xx and 5xx errors.

app.get('/smth', function(req, res, next){
   if (!smth-check)
      return next(new HttpError(401, 'Error-text')); // it's custom error class
   ...
})

app.use(function(err, req, res, next)) {
   if (err instance of HttpError)
       console.log(err.status);
   ...
});

About custom error as HttpError you can read here

Community
  • 1
  • 1
Aikon Mogwai
  • 4,954
  • 2
  • 18
  • 31
1

Your logic was right, you just need to call next before getting the status, so that other middlewares / your route can set the status code:

const fooMiddleware = (req, res, next) => {
  req.stats.totalRequestsServed += 1;
  next();
  console.log('status code', res.statusCode);
};
Iso
  • 3,148
  • 23
  • 31
0

I found a package called on-finished that manage this also adding a listener. It could be use like this:

const onFinished = require('on-finished');

const middleware = (req, res, next) => {

  onFinished(res, (err, res) => {
    // do smth after res.send
  });

  // do smth before request eventually calling `next()`
  next(null);
};
Nicolas Del Valle
  • 1,384
  • 15
  • 20