Xerri Xerri - 4 months ago 80
Node.js Question

Express.js Response Timeout


I've been looking for request/response timeouts for Express.js but everything seems to be related to the connection rather than the request/response itself.

If a request is taking a long time, it should be timed out. Obviously this shouldn't happen but even a simple mistake as having a route handler without a call to the callback or without

, the browser will keep waiting for a reply forever.

An empty route handler is a perfect example of this.

app.get('/sessions/', function(req, res, callback){});


I added the following before
and it seemed to add the timeout functionality. Does anyone have any experience/opinion on this?

app.use(function(req, res, next){
res.setTimeout(120000, function(){
console.log('Request has timed out.');


Note that I've set the timeout to 2 minutes.


There is already a Connect Middleware for Timeout support:

var timeout = express.timeout // express v3 and below
var timeout = require('connect-timeout'); //express v4


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.