Nicolas Del Valle Nicolas Del Valle - 4 months ago 7
Node.js Question

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.

Answer

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