0
0
Expressframework~30 mins

Response time tracking middleware in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Response time tracking middleware
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use a template string with console.log to show method, URL, and time with two decimals.