📖 Scenario: You are building a simple Express server that needs to track how long each request takes to process. This helps understand server performance and improve user experience.
🎯 Goal: Create an Express middleware that measures and logs the response time for each incoming request.
📋 What You'll Learn
Create an Express app with a basic route
Add a middleware to record the start time of the request
Calculate the response time after the response finishes
Log the response time with the request method and URL
💡 Why This Matters
🌍 Real World
Tracking response times helps developers monitor server performance and identify slow endpoints.
💼 Career
Middleware development and performance monitoring are common tasks for backend developers working with Express.
Progress0 / 4 steps
1
Set up Express app with a basic route
Create an Express app by requiring express and calling express(). Then add a GET route for '/' that sends the text 'Hello World'.
Express
Hint
Use require('express') to import Express and express() to create the app. Then use app.get to add a route.
2
Add middleware to record start time
Add a middleware using app.use that sets req.startTime to process.hrtime() at the beginning of each request.
Express
Hint
Use app.use to add middleware. Use process.hrtime() to get high-resolution time and store it on req.startTime.
3
Calculate response time after response finishes
Inside the middleware, listen for the 'finish' event on res. When it fires, calculate the difference between current process.hrtime() and req.startTime to get the response time in milliseconds.
Express
Hint
Use res.on('finish', callback) to run code after response ends. Use process.hrtime(req.startTime) to get elapsed time.
4
Log the response time with method and URL
Inside the 'finish' event handler, add a console.log statement that outputs the HTTP method, URL, and response time in milliseconds with a message like: "GET / took 12.34 ms".
Express
Hint
Use a template string with console.log to show method, URL, and time with two decimals.
Practice
(1/5)
1. What is the main purpose of response time tracking middleware in Express?
easy
A. To measure how long each HTTP request takes to complete
B. To modify the request body before processing
C. To handle errors and send error responses
D. To serve static files like images and CSS
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 A
Quick Check:
Response time tracking = measuring request duration [OK]
Hint: Middleware timing tracks request duration, not request content [OK]
Common Mistakes:
Confusing response time tracking with error handling
Thinking it modifies request data
Assuming it serves static files
2. Which of the following is the correct way to start measuring time in an Express middleware?
easy
A. const start = setTimeout();
B. const start = Date.now();
C. const start = process.hrtime();
D. const start = new Date().toString();
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 B
Quick Check:
Use Date.now() for simple timestamps [OK]
Hint: Use Date.now() for simple time stamps in middleware [OK]
Common Mistakes:
Using new Date().toString() which returns a string
Confusing process.hrtime() with Date.now()
Using setTimeout() incorrectly for timing
3. Given this middleware snippet, what will be logged?
B. Using Date.now() instead of process.hrtime() causes error
C. res.on('finish') should be res.on('end')
D. Missing call to next(), so request hangs
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 D
Quick Check:
Always call next() in middleware [OK]
Hint: Always call next() to continue middleware chain [OK]
Common Mistakes:
Forgetting next() call
Confusing 'finish' with 'end' event
Thinking Date.now() causes errors
5. You want to log the response time in milliseconds to the console using the format Request took ${duration}ms. Which middleware code correctly does this?
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 A