Express.js Response Timeout
There is already a Connect Middleware for Timeout support:
var timeout = express.timeout // express v3 and belowvar timeout = require('connect-timeout'); //express v4app.use(timeout(120000));app.use(haltOnTimedout);function haltOnTimedout(req, res, next){ if (!req.timedout) next();}
If you plan on using the Timeout middleware as a top-level middleware like above, the haltOnTimedOut
middleware needs to be the last middleware defined in the stack and is used for catching the timeout event. Thanks @Aichholzer for the update.
Side Note:
Keep in mind that if you roll your own timeout middleware, 4xx status codes are for client errors and 5xx are for server errors. 408s are reserved for when:
The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.
You don't need other npm modules to do this
var server = app.listen();server.setTimeout(500000);
inspired by https://github.com/expressjs/express/issues/3330
or
app.use(function(req, res, next){ req.setTimeout(500000, function(){ // call back function is called when request timed out. }); next();});
An update if one is using Express 4.2 then the timeout middleware has been removed so need to manually add it with
npm install connect-timeout
and in the code it has to be (Edited as per comment, how to include it in the code)
var timeout = require('connect-timeout'); app.use(timeout('100s'));