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:
const start = Date.now()- Records the current time when the request startsres.on('finish', ...)- Sets up an event listener that waits for the response to complete- When the response finishes, the callback function runs and calculates the duration
Date.now() - start- Calculates how many milliseconds have passed- The result is logged to the console showing the request method, URL, and duration
This gives you timing information for every request.