To add Express.js response timeout with Node.js, we use the connect-timeout
module.
For instance, we write
const timeout = require("connect-timeout");
const haltOnTimedout = (req, res, next) => {
if (!req.timedout) {
next();
}
};
app.use(timeout(120000));
app.use(haltOnTimedout);
to add the halfOnTimedout
function.
In it, we check if the request timed out with req.timedout
.
If it’s false
, then we call next
to call the next middleware.
Then we call app.use
to add the timeout
middleware to make requests time out after 120000ms.
And we call app.use
again to add the haltOnTimedout
middleware.