0
0
Expressframework~10 mins

Response time tracking middleware in Express - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Response time tracking middleware
Request received
Middleware start timer
Pass control to next middleware/handler
Response sent back
Middleware calculates elapsed time
Log or store response time
End
The middleware starts a timer when a request arrives, lets the request process, then calculates and logs the response time after the response is sent.
Execution Sample
Express
app.use((req, res, next) => {
  const start = Date.now();
  res.on('finish', () => {
    const duration = Date.now() - start;
    console.log(`Response time: ${duration}ms`);
  });
  next();
});
This middleware measures how long it takes to handle a request and logs the response time in milliseconds.
Execution Table
StepActionEvaluationResult
1Request arrivesStart timer with Date.now()start = 1000 (example)
2Set 'finish' event listenerres.on('finish', callback)Listener registered
3Call next()Pass control to next middleware/handlerRequest processing continues
4Response finishesres emits 'finish' eventTrigger callback
5Calculate durationDate.now() - startduration = 1050 - 1000 = 50ms
6Log durationconsole.log outputResponse time: 50ms
7EndMiddleware completesResponse sent with timing logged
💡 Response finished, middleware logged duration and completed
Variable Tracker
VariableStartAfter Step 1After Step 5Final
startundefined100010001000
durationundefinedundefined5050
Key Moments - 2 Insights
Why do we use the 'finish' event on the response object?
Because the 'finish' event fires when the response is fully sent, ensuring the timing includes the entire request handling, as shown in execution_table step 4.
Why do we call next() after setting up the 'finish' event?
We call next() to let the request continue processing, but we set up the 'finish' event listener before calling next() to catch when the response ends, as seen in execution_table steps 2 and 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'duration' at step 5?
A50ms
B1000ms
Cundefined
D1050ms
💡 Hint
Check the 'Calculate duration' row in the execution_table where duration is computed as 1050 - 1000.
At which step does the middleware allow the request to continue processing?
AStep 1
BStep 3
CStep 4
DStep 6
💡 Hint
Look at the 'Call next()' action in the execution_table.
If the 'finish' event listener was set after calling next(), what might happen?
AThe timer would start too late.
BThe response time would be logged twice.
CThe listener might miss the 'finish' event and not log the response time.
DThe middleware would block the request.
💡 Hint
Refer to key_moments about why the 'finish' event listener is set before next().
Concept Snapshot
Response time middleware in Express:
- Start timer on request arrival
- Use res.on('finish') to detect response end
- Calculate duration = Date.now() - start
- Log or store duration
- Call next() to continue processing
Ensures full request-response timing is captured.
Full Transcript
This middleware tracks how long a request takes in Express. When a request arrives, it records the current time. It then sets a listener on the response's 'finish' event, which fires when the response is fully sent. When 'finish' triggers, it calculates the elapsed time by subtracting the start time from the current time. Finally, it logs the response time in milliseconds. The middleware calls next() after setting up the listener to let the request continue processing, ensuring it catches the response completion. This way, the middleware accurately measures the total time taken to handle the request and send the response.