Why does listening to an event make a more accurate response time measurement in Express.js?

I’ve written an Express.js middleware to measure an endpoint’s response time that looks like this:

export function metricsMiddleware(req: Request, res: Response, next: NextFunction) {
  const startTime = Date.now();
  next();
  const durationMillis = Date.now() - startTime;
  console.log(durationMillis);
}

The values output are suspiciously low, in the range of sub-millisecond. I’m seeing an alternative approach to write it like:

export function metricsMiddleware(req: Request, res: Response, next: NextFunction) {
  const startTime = Date.now();
  res.on("finish", () => {
    const durationMillis = Date.now() - startTime;
    console.log(durationMillis);
  })
  next();
}

Why does the second approach work, while the first approach does not?

>Solution :

Because code executed by next() (which is whatever comes next after your middleware) may or may not be synchronous.

If everything after your middleware is synchronous (does not fetch anything from db etc) then it will be accurate.

But if you have anything asynchronous after the middleware then your console.log() will obviously execute befor next() is finished.

Leave a Reply