0
0
Expressframework~5 mins

Response time tracking middleware in Express

Choose your learning style9 modes available
Introduction

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.

You want to check if your website loads quickly for users.
You need to find slow parts in your server to improve them.
You want to log response times for monitoring or debugging.
You are testing new features and want to compare speed.
You want to add response time info to HTTP headers for clients.
Syntax
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.

Examples
Adds the middleware to all routes in your Express app.
Express
app.use(responseTimeMiddleware);
You can add the response time to a custom HTTP header for clients to see.
Express
res.setHeader('X-Response-Time', `${duration}ms`);
Use high-resolution timer for more precise timing in nanoseconds converted to milliseconds.
Express
const start = process.hrtime.bigint();
// ... later
const duration = Number(process.hrtime.bigint() - start) / 1_000_000;
Sample Program

This Express app uses the response time middleware to log how long each request takes. The '/' route waits 100ms before responding to simulate work.

Express
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');
});
OutputSuccess
Important Notes

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.

Summary

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.