How To Handle Etimedout Node.Js [Solved]

Issue Root Cause Recommended Fix
ETIMEDOUT Unstable WiFi or Network Latency Increase timeout limits and implement retry logic.

Node.js ETIMEDOUT error illustration with network signal symbols.

What is ETIMEDOUT in Node.js?

The ETIMEDOUT error occurs when a Node.js application attempts to establish a connection with a remote server, but the server fails to respond within the allotted time frame. This is a TCP-layer error indicating that the handshake process could not be completed.

In the context of WiFi drops, this error is common. When your local wireless connection fluctuates or disconnects briefly, the network packets are lost. Node.js waits for a response that never arrives, eventually throwing the ETIMEDOUT exception to prevent the process from hanging indefinitely.

Step-by-Step Solutions

1. Increase Request Timeouts

By default, some Node.js HTTP clients have short timeout periods. Increasing these can help the application survive momentary WiFi jitters.

If you are using the native `http` module, you can set the timeout explicitly on the request object.


const http = require('http');

const options = {
  hostname: 'example.com',
  port: 80,
  path: '/',
  method: 'GET',
  timeout: 10000 // Set timeout to 10 seconds
};

const req = http.request(options, (res) => {
  // Handle response
});

req.on('timeout', () => {
  req.destroy();
  console.error('Request timed out due to network instability.');
});

req.end();

2. Implement Exponential Backoff Retries

When WiFi drops occur, a single retry might fail if the connection hasn’t recovered yet. Implementing a retry strategy with exponential backoff is the most robust way to handle ETIMEDOUT.

You can use libraries like `axios-retry` or write a custom loop that waits longer after each failed attempt. This gives the WiFi hardware time to reconnect before the next request is sent.

3. Check Local Network Stability

If ETIMEDOUT occurs frequently, the issue might be your environment rather than the code. Monitor your WiFi signal strength and packet loss.

Use the following command in your terminal to check for packet loss during a Node.js session:


ping -t 8.8.8.8

If you see “Request timed out” in your terminal at the same time your Node.js app fails, the problem is verified as a local network drop.

4. Use Keep-Alive Headers

Enabling HTTP Keep-Alive allows you to reuse the same TCP connection for multiple requests. This reduces the need for new handshakes, which are the most vulnerable stage during a WiFi drop.

In Node.js, you can use an `Agent` to manage persistent connections:


const http = require('http');
const keepAliveAgent = new http.Agent({ keepAlive: true });

http.request({
  hostname: 'example.com',
  agent: keepAliveAgent
}, (res) => {
  // ...
});