[node.js] 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.

This question is related to node.js express timeout response settimeout

The answer is


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
});

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.


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

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


Before you set your routes, add the code:

app.all('*', function(req, res, next) {
    setTimeout(function() {
        next();
    }, 120000); // 120 seconds
});

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){
    res.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'));

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to express

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block jwt check if token expired Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] npm notice created a lockfile as package-lock.json. You should commit this file Make Axios send cookies in its requests automatically What does body-parser do with express? SyntaxError: Unexpected token function - Async Await Nodejs Route.get() requires callback functions but got a "object Undefined" How to redirect to another page in node.js

Examples related to timeout

Waiting for Target Device to Come Online Spring Boot Java Config Set Session Timeout How to dispatch a Redux action with a timeout? Spring Boot REST API - request timeout? 5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error How to set timeout in Retrofit library? How to set connection timeout with OkHttp How to modify the nodejs request default timeout time? How to handle ETIMEDOUT error? Timeout for python requests.get entire response

Examples related to response

Returning JSON object as response in Spring Boot Guzzlehttp - How get the body of a response from Guzzle 6? Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest Express.js Response Timeout What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response) Return generated pdf using spring MVC Create HTTP post request and receive response using C# console application java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed C# Encoding a text string with line breaks Remove Server Response Header IIS7

Examples related to settimeout

setInterval in a React app setTimeout in React Native Combination of async function + await + setTimeout How to make a promise from setTimeout How to make `setInterval` behave more in sync, or how to use `setTimeout` instead? Express.js Response Timeout Difference between setTimeout with and without quotes and parentheses How to stop a setTimeout loop? How to make a jquery function call after "X" seconds What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?