How to log the response body with Express?

Sometimes, we want to log the response body with Express.

In this article, we’ll look at how to log the response body with Express.

How to log the response body with Express?

To log the response body with Express, we can create our own middleware to intercept the response and log it.

For instance, we write

const logResponseBody = (req, res, next) => {
  const oldWrite = res.write
  const oldEnd = res.end;

  const chunks = [];

  res.write = (chunk, ...args) => {
    chunks.push(chunk);
    return oldWrite.apply(res, [chunk, ...args]);
  };

  res.end = (chunk, ...args) => {
    if (chunk) {
      chunks.push(chunk);
    }
    const body = Buffer.concat(chunks).toString('utf8');
    console.log(req.path, body);
    return oldEnd.apply(res, [chunk, ...args]);
  };

  next();
}

app.use(logResponseBody);

to create the logResponseBody middleware function that sets res.write to a function that calls chunks.push to push the response chunks to the chunks array.

And then we return the result of the original res.write write method, which is stored in oldWrite.

Likewise, we set res.end to a method that combine the chunks into a buffer with Buffer.concat.

And then we log the body with console.log.

And then we call oldEnd.apply and return the results.

Finally, we call next to call the next middleware.

Conclusion

To log the response body with Express, we can create our own middleware to intercept the response and log it.