How do I set a timeout for client http connections in node.js

Tag: node.js Author: wygn2009 Date: 2010-08-11

I'm writing a node.js application that needs to talk to a server. It establishes an http connection with the following code:

var client = http.createClient(u.port, u.hostname,;
client.on("error", function(exception) {
    logger.error("error from client");
var request = client.request(method, u.path, headers);

I don't see any option in the node.js documentation for setting a timeout on the connection, and it seems to be set to 20 seconds by default. The problem I'm having is that I have users in China on what appears to be a slow or flaky network, who sometimes hit the timeout connecting to our datacenter in the US. I'd like to increase the timeout to 1 minute, to see if that fixes it for them.

Is there a way to do that in node.js?


The correct answers are all in this duplicate question: click me (especially see douwe's answer)

Other Answer1


request.socket.setTimeout(60000); // 60 sec


That is the right answer with node edge at least...

Other Answer2

I think you can do something like:


request.connection returns the net.Stream object associated with the connection. and net.Stream has a setTimeout method.


Doesn't work. I also found there's a client.setTimeout() method, that doesn't work either. I think these are timeouts for traffic on the connection, not for establishing the connection.
Right. Ok then ... I will have another trawl through some code. Might be worth checking how/if some of the node frameworks handle this.
Thanks that solved a WebSocket proxy problem for me ;) The connections were dead after a minute or so.

Other Answer3

You have to wait for the client socket connection to be established first, before setting the timeout. To do this, add a callback for the 'socket' event:

req.on('socket', function (socket) {
    myTimeout = 500; // millis
    socket.on('timeout', function() {
        console.log("Timeout, aborting request")
}).on('error', function(e) {
    console.log("Got error: " + e.message);
    // error callback will receive a "socket hang up" on timeout

See this answer.