Bird
Raised Fist0
Expressframework~10 mins

Response time tracking middleware in Express - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a middleware function that records the start time.

Express
function responseTimeTracker(req, res, next) {
  req.startTime = [1];
  next();
}
Drag options to blanks, or click blank then click option'
Aperformance.now()
Bnew Date().getTime()
CDate.now()
Dprocess.hrtime()
Attempts:
3 left
💡 Hint
Common Mistakes
Using process.hrtime() returns an array, not a timestamp.
Using performance.now() is not available in all Node.js versions.
2fill in blank
medium

Complete the code to calculate the response time in milliseconds after the response finishes.

Express
function responseTimeTracker(req, res, next) {
  req.startTime = Date.now();
  res.on('finish', () => {
    const duration = [1] - req.startTime;
    console.log(`Response time: ${duration}ms`);
  });
  next();
}
Drag options to blanks, or click blank then click option'
Anew Date()
BDate.now()
Cperformance.now()
Dprocess.hrtime()
Attempts:
3 left
💡 Hint
Common Mistakes
Using new Date() returns a Date object, not a number.
Using process.hrtime() returns an array, not a number.
3fill in blank
hard

Fix the error in the middleware to correctly log the response time in seconds with two decimals.

Express
function responseTimeTracker(req, res, next) {
  req.startTime = Date.now();
  res.on('finish', () => {
    const duration = (Date.now() - req.startTime) / [1];
    console.log(`Response time: ${duration.toFixed(2)}s`);
  });
  next();
}
Drag options to blanks, or click blank then click option'
A60
B10000
C100
D1000
Attempts:
3 left
💡 Hint
Common Mistakes
Dividing by 60 converts to minutes, not seconds.
Dividing by 100 or 10000 gives incorrect time units.
4fill in blank
hard

Fill both blanks to create a middleware that adds a custom header with the response time in milliseconds.

Express
function responseTimeTracker(req, res, next) {
  req.startTime = Date.now();
  res.on('[1]', () => {
    const duration = Date.now() - req.startTime;
    res.setHeader('[2]', duration + 'ms');
  });
  next();
}
Drag options to blanks, or click blank then click option'
Afinish
Bclose
Cresponse-time
DX-Response-Time
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'close' event may not always indicate response finished.
Using 'response-time' as header name is uncommon and may not be recognized.
5fill in blank
hard

Fill all three blanks to create a complete Express app using the response time middleware and a simple route.

Express
const express = require('express');
const app = express();

function responseTimeTracker(req, res, next) {
  req.startTime = Date.now();
  res.on('[1]', () => {
    const duration = Date.now() - req.startTime;
    res.setHeader('[2]', duration + 'ms');
  });
  next();
}

app.use([3]);

app.get('/', (req, res) => {
  res.send('Hello World');
});

app.listen(3000);
Drag options to blanks, or click blank then click option'
Afinish
BX-Response-Time
CresponseTimeTracker
Dclose
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'close' event instead of 'finish'.
Forgetting to pass the middleware function to app.use.

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

  1. Step 1: Understand middleware role

    Response time tracking middleware measures the duration of requests.
  2. Step 2: Identify main purpose

    It tracks how long the server takes to respond to each request.
  3. Final Answer:

    To measure how long each HTTP request takes to complete -> Option A
  4. 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

  1. Step 1: Identify time measurement method

    Date.now() returns the current timestamp in milliseconds, suitable for timing.
  2. 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.
  3. Final Answer:

    const start = Date.now(); -> Option B
  4. 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?
app.use((req, res, next) => {
  const start = Date.now();
  res.on('finish', () => {
    const duration = Date.now() - start;
    console.log(`Request took ${duration}ms`);
  });
  next();
});
medium
A. Logs the time before the request starts processing
B. Logs the time repeatedly during the request
C. Logs the time taken for each request after response finishes
D. Does not log anything because of missing next()

Solution

  1. Step 1: Understand event listener on 'finish'

    The 'finish' event triggers after the response is sent, so timing is complete.
  2. Step 2: Calculate duration and log

    Duration is current time minus start time, logged once per request.
  3. Final Answer:

    Logs the time taken for each request after response finishes -> Option C
  4. Quick Check:

    res.on('finish') logs after response ends [OK]
Hint: res.on('finish') runs after response ends for timing [OK]
Common Mistakes:
  • Thinking it logs before request processing
  • Assuming multiple logs during request
  • Forgetting to call next() to continue middleware chain
4. Identify the error in this response time middleware:
app.use((req, res, next) => {
  const start = Date.now();
  res.on('finish', () => {
    const duration = Date.now() - start;
    console.log(`Request took ${duration}ms`);
  });
});
medium
A. Logging inside middleware is not allowed
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

  1. Step 1: Check middleware flow

    Middleware must call next() to pass control; missing here causes request to hang.
  2. Step 2: Validate event and logging

    res.on('finish') is correct event; Date.now() is valid; logging is allowed.
  3. Final Answer:

    Missing call to next(), so request hangs -> Option D
  4. 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?
hard
A. app.use((req, res, next) => { const start = Date.now(); res.on('finish', () => { const duration = Date.now() - start; console.log(`Request took ${duration}ms`); }); next(); });
B. app.use((req, res, next) => { const start = Date.now(); const duration = Date.now() - start; console.log(`Request took ${duration}ms`); next(); });
C. app.use((req, res, next) => { const start = Date.now(); console.log(`Request took ${Date.now() - start}ms`); next(); });
D. app.use((req, res, next) => { const start = Date.now(); res.on('close', () => { const duration = Date.now() - start; console.log(`Request took ${duration}ms`); }); next(); });

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    Uses res.on('finish') to log accurate request duration -> Option A
  4. Quick Check:

    res.on('finish') ensures complete request timing [OK]
Hint: Log duration in 'finish' event after response completes [OK]
Common Mistakes:
  • Logging before calling next() (duration ~0ms)
  • Using 'close' event instead of 'finish'
  • Not waiting for response to finish
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard