Calculating NodeJS API Response Time

01-16-2020

It’s important to have as much information about the speed and health of our applications when they are running in the wild. In this blog post I’ll show you how to create a simple response time middleware that calculates the total time it takes for your application to process a request. By using the process hr time API we can calculate the total elapsed time between when first capture the startTime and when the request ‘finishes’.

app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const express = require('express');
const app = express();

const responseTime = require('./response-time');

app.use(responseTime);

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

const server = app.listen(5000, () => {
console.log(`Server is listening on port ${server.address().port}`);
});

response-time.js

1
2
3
4
5
6
7
8
9
10
11
12
13
const responseTime = ((req, res, next)=>{
const startTime = process.hrtime();

res.on('finish', ()=>{
const totalTime = process.hrtime(startTime);
const totalTimeInMs = totalTime[0] * 1000 + totalTime[1] / 1e6;
console.log(totalTimeInMs);
});

next();
})

module.exports = responseTime;

* Inspired by this blog post