Nicolas Del Valle Nicolas Del Valle - 2 months ago 6x
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);

I'm using the code above but I'm always getting a
status code, even If I hardcode a
on my route.


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

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

    // do smth before request eventually calling `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)

About custom error as HttpError you can read here