This middleware helps you see how long your server takes to answer each request. It shows the time in milliseconds so you can know if your app is fast or slow.
Response time tracking middleware in Express
function responseTimeMiddleware(req, res, next) {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
console.log(`${req.method} ${req.url} took ${duration}ms`);
});
next();
}The middleware uses res.on('finish') to run code after the response is sent.
next() is called to pass control to the next middleware or route.
app.use(responseTimeMiddleware);
res.setHeader('X-Response-Time', `${duration}ms`);
const start = process.hrtime.bigint();
// ... later
const duration = Number(process.hrtime.bigint() - start) / 1_000_000;This Express app uses the response time middleware to log how long each request takes. The '/' route waits 100ms before responding to simulate work.
import express from 'express'; const app = express(); function responseTimeMiddleware(req, res, next) { const start = Date.now(); res.on('finish', () => { const duration = Date.now() - start; console.log(`${req.method} ${req.url} took ${duration}ms`); }); next(); } app.use(responseTimeMiddleware); app.get('/', (req, res) => { setTimeout(() => { res.send('Hello, world!'); }, 100); // simulate delay }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Response time includes the time your server spends processing plus sending the response.
Use res.on('finish') instead of res.on('close') to ensure the response was fully sent.
Adding the response time header helps frontend developers see performance without checking logs.
Response time middleware measures how long each request takes.
It uses res.on('finish') to run code after response ends.
You can log times and add them to HTTP headers for easy monitoring.
Practice
Solution
Step 1: Understand middleware role
Response time tracking middleware measures the duration of requests.Step 2: Identify main purpose
It tracks how long the server takes to respond to each request.Final Answer:
To measure how long each HTTP request takes to complete -> Option AQuick Check:
Response time tracking = measuring request duration [OK]
- Confusing response time tracking with error handling
- Thinking it modifies request data
- Assuming it serves static files
Solution
Step 1: Identify time measurement method
Date.now() returns the current timestamp in milliseconds, suitable for timing.Step 2: Check other options
new Date().toString() returns a string, not a number; process.hrtime() returns a tuple, more complex; setTimeout() is for delays, not time capture.Final Answer:
const start = Date.now(); -> Option BQuick Check:
Use Date.now() for simple timestamps [OK]
- Using new Date().toString() which returns a string
- Confusing process.hrtime() with Date.now()
- Using setTimeout() incorrectly for timing
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
console.log(`Request took ${duration}ms`);
});
next();
});Solution
Step 1: Understand event listener on 'finish'
The 'finish' event triggers after the response is sent, so timing is complete.Step 2: Calculate duration and log
Duration is current time minus start time, logged once per request.Final Answer:
Logs the time taken for each request after response finishes -> Option CQuick Check:
res.on('finish') logs after response ends [OK]
- Thinking it logs before request processing
- Assuming multiple logs during request
- Forgetting to call next() to continue middleware chain
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
console.log(`Request took ${duration}ms`);
});
});Solution
Step 1: Check middleware flow
Middleware must call next() to pass control; missing here causes request to hang.Step 2: Validate event and logging
res.on('finish') is correct event; Date.now() is valid; logging is allowed.Final Answer:
Missing call to next(), so request hangs -> Option DQuick Check:
Always call next() in middleware [OK]
- Forgetting next() call
- Confusing 'finish' with 'end' event
- Thinking Date.now() causes errors
Request took ${duration}ms. Which middleware code correctly does this?Solution
Step 1: Understand logging timing
To capture the full request processing time, record the start time, call next(), and log the duration in the 'finish' event handler which fires after the response is sent.Step 2: Analyze incorrect approaches
Logging right after starting the timer yields nearly 0ms because handlers haven't executed yet. The 'close' event relates to connection closure, not response completion, and may not fire reliably for timing.Final Answer:
Uses res.on('finish') to log accurate request duration -> Option AQuick Check:
res.on('finish') ensures complete request timing [OK]
- Logging before calling next() (duration ~0ms)
- Using 'close' event instead of 'finish'
- Not waiting for response to finish
Ready to prove it?
Pass the test and this pattern moves unknown
