Now let’s create our own middleware function that measures how long each request takes:

// Request timing middleware
app.use((req, res, next) => {
  const start = Date.now();

  res.on("finish", () => {
    const duration = Date.now() - start;
    console.log(`${req.method} ${req.url} - ${duration}ms`);
  });

  next();
});

How it works:

  1. const start = Date.now() - Records the current time when the request starts
  2. res.on('finish', ...) - Sets up an event listener that waits for the response to complete
  3. When the response finishes, the callback function runs and calculates the duration
  4. Date.now() - start - Calculates how many milliseconds have passed
  5. The result is logged to the console showing the request method, URL, and duration

This gives you timing information for every request.



Repo link

Tags: