Nicolas Del Valle
Nicolas Del Valle

Reputation: 1484

How to access the response code sent to the client of an Expressjs app

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.

Upvotes: 1

Views: 1499

Answers (3)

Iso
Iso

Reputation: 3238

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);
};

Upvotes: 1

Nicolas Del Valle
Nicolas Del Valle

Reputation: 1484

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);
};

Upvotes: 0

Aikon Mogwai
Aikon Mogwai

Reputation: 5225

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

Upvotes: 1

Related Questions