Automatically Log or Append Data to Express Response

Sometimes you need to log Express response in order to see what your application responded with. Doing it for each route can be tedious. A better approach is to use a middleware. The middleware also gives you the flexibility to choose responses from which routes to log. When you have access to your response in the middleware, you can also append meta data for all of the routes that have the middleware. Let’s take a look at the example below.

import { v4 as uuidv4 } from 'uuid';
import { Request, Response, NextFunction } from 'express';
import logger from '../services/logger';

const requestLogger = (req: Request, res: Response, next: NextFunction) => {
  const logId = uuidv4();
  req.logId = logId;
  logger.info(`Webhook request: ${logId}`);
  // Obfuscate PII data
  logger.info(JSON.stringify(req.body));
  const oldSend = res.send;
  res.send = (data) => {
    const parsedData = JSON.parse(data);
    parsedData.log_id = logId;
    logger.info(`Webhook response: ${logId}`);
    logger.info(JSON.stringify(parsedData));
    res.send = oldSend;
    return res.send(parsedData);
  };
  next();
};

export default requestLogger;

You can use the middleware above for webhook routes. It creates a unique log id and attaches it to the request. Use this log id when logging transactional information about a webhook. Next, the middleware logs the request’s body. Please, be sure to obfuscate or replace any PII or sensitive information, such as tokens. Finally, the middleware attaches the log id and also logs express response.

This middleware helps you identify transactional logs for a specific webhook request to troubleshoot any issues.

Share this article

Similar Posts