Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js Response Timeout

PROBLEM

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 res.send(), 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){}); 

FIX

I added the following before app.use(app,router); 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.');             res.send(408);         });      next(); }); 

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

like image 684
Xerri Avatar asked Feb 11 '14 17:02

Xerri


People also ask

How do I increase my express timeout?

Simply put, you need to configure the timeout value on the HTTP Server that express generates when you call the listen method. For example: // create an express app const app = express(); // add a route that delays response for 3 minutes app. get('/test', (req, res) => { setTimeout(() => { res.

What is Express default timeout?

The default for 6. x is 2 minutes. You can use server. setTimeout(msecs) to set a different default timeout on the server. I hope this helps!


2 Answers

There is already a Connect Middleware for Timeout support:

var timeout = express.timeout // express v3 and below var timeout = require('connect-timeout'); //express v4  app.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.

like image 100
srquinn Avatar answered Oct 26 '22 19:10

srquinn


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(); }); 
like image 21
bereket gebredingle Avatar answered Oct 26 '22 20:10

bereket gebredingle