To add a response timeout feature to an Express.js app to end requests that take too long to process, we can use the connect-timeout
package.
To install it, we run:
npm i `connect-timeout`
Then we can use it by writing:
const express = require('express')
const timeout = require('connect-timeout');
const app = express()
const port = 3000
const haltOnTimedout = (req, res, next) => {
if (!req.timedout) {
next();
}
}
app.use(timeout(120000));
app.use(haltOnTimedout);
app.get('/', (req, res) => {
res.send('hello world')
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
We include the module with require
.
Then we create the haltOnTimeout
function that checks the req.timedout
property to see if the request has timed out.
If it hasn’t timed out, then req.timedout
is false
and we call next
to move forward with the request.
This property is available which we added:
app.use(timeout(120000));
to add the connect-timeout
middleware to detect the timeout.
120000 is in milliseconds and it’s the number of milliseconds before the request times out.