105

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.

6
  • 2
    I would use this for development purposes only – I can't think of a single use case where you would want to ship production code with empty routes.
    – srquinn
    Feb 11, 2014 at 17:11
  • If course, my point with that is that its possible to have an issue where the request would just keep waiting. Bugs happen. I'm just trying to set a response timeout just in case.
    – Xerri
    Feb 11, 2014 at 17:14
  • Gotcha – see answer below
    – srquinn
    Feb 11, 2014 at 17:29
  • 10
    empty routes as a trap for web spiders?
    – prototype
    Oct 23, 2015 at 17:06
  • This 'feature' actually came quite useful when I was trying to use Express.js (well, actually json-server) to build a test service with the purpose of simulating / inducing all manners of error conditions on the server side. Most such errors corresponded to HTTP status codes (e.g. Bad Request), yes, but I also wanted to cause a SocketTimeoutException on the caller end. Mar 8, 2018 at 13:17

9 Answers 9

87

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.

11
  • Perfect. Even simpler. Thanks for the tip on the error message as well.
    – Xerri
    Feb 11, 2014 at 17:34
  • 3
    According to the official documentation, using it as top-level middleware is not recommended, at least not just like that. github.com/expressjs/timeout
    – Stefan
    Sep 3, 2014 at 9:12
  • This answer seems to be fairly useless without increasing the socket timeout. stackoverflow.com/questions/12651466/… Jan 20, 2015 at 1:25
  • @JeffFischer: calling socket.setTimeout() only increases the time before the timeout event is called but the connection is not severed by default nodejs.org/api/net.html#net_socket_settimeout_timeout_callback. In node v0.9.12, a setTimeout API was added to the http.server object to handle the functionality of this middleware in the node standard http lib. However, before that API update this middleware would handle destroying the socket. You can read more on the innards of the middleware here github.com/expressjs/timeout/blob/master/index.js
    – srquinn
    Jan 20, 2015 at 2:22
  • 1
    @SuperUberDuper: Please post you query as a separate question so the community can help you with your specific issue.
    – srquinn
    Jun 10, 2016 at 19:07
83

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();
});
5
  • This is a very old post but I didn’t use any extra modules. Check out the ‘fix’ part in the question
    – Xerri
    Oct 23, 2018 at 8:46
  • req.setTimeout not res.setTimeout Mar 20, 2021 at 10:28
  • My experiments show that req.setTimeout() callback is not getting called at all and the server.setTimeout() is not closing the connection and is not stopping the request from being processed. So the provided solution is not complete. Jul 26, 2021 at 13:48
  • 2
    My test have req.setTimeout and res.setTimeout both working. Aug 27, 2021 at 3:22
  • 2
    res.setTimeout worked for me not req Feb 22, 2022 at 22:01
36

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'));
1
  • 1
    Didn't DV, but some people probably need to use var timeout = require('connect-timeout') and had to search google for it =) Mar 11, 2018 at 4:00
5

In case you would like to use timeout middleware and exclude a specific route:

var timeout = require('connect-timeout');
app.use(timeout('5s')); //set 5s timeout for all requests

app.use('/my_route', function(req, res, next) {
    req.clearTimeout(); // clear request timeout
    req.setTimeout(20000); //set a 20s timeout for this request
    next();
}).get('/my_route', function(req, res) {
    //do something that takes a long time
});
1

If you need to test your api, this solotion can you help. I used this in middleware to test my frontend. For exmaple: if you need to test loader in frontend.

const router = require('express').Router();
const { data } = require('./data');

router.get('/api/data', (req, res, next) => {
  setTimeout(() => {
      res.set('Content-Type', 'application/json')
      res.status(200).send(data)

      next()
  }, 2000)
})

module.exports = router;
0

I hope it's not too late, this is a solution that I got from @Elliot404, and it's what I was looking for. I hope it helps.

export const timeOutMiddleWare = (
  req: Request,
  res: Response,
  next: NextFunction,
) => {
  setTimeout(() => {
    if (!res.headersSent) {
      res.status(408).send(`${req.method} ${req.originalUrl} Timed Out`);
      req.socket.end();
      res.json = () => {};
      res.send = () => {};
      res.sendStatus = () => {};
    }
  }, 1000 * 60 * 5);
  next();
};
-1

request.setTimeout(< time in milliseconds >) does the job

https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback

-3

You can try:

return await new Promise((resolve) =>
  setTimeout(() => {
    resolve(resp);
  }, 3000),
);

In above code, 3000 = 3 sec. Change it according to your requirement.

I have not tried for very long scenarios though. Let me know the results in comments.

-20

Before you set your routes, add the code:

app.all('*', function(req, res, next) {
    setTimeout(function() {
        next();
    }, 120000); // 120 seconds
});
3
  • 34
    Isn't this just waiting for 120 second before ever replying to the client? Jun 13, 2017 at 9:48
  • 5
    @JeffreyvanNorden That's what I'm looking for, for debugging purpose. May 22, 2019 at 16:29
  • 2
    Ironically this is exactly what I was looking for. Oct 17, 2021 at 18:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.