Node.Js Keepalive Settings For Unstable Wifi [Solved]

Setting Recommended Value Impact on Unstable WiFi
keepAlive true Prevents socket closure between requests.
keepAliveMsecs 1000ms – 5000ms Sends frequent probes to detect silent drops.
timeout 60000ms+ Allows for temporary latency spikes.

Node.js keepalive configuration for unstable internet connections.

What is node.js keepalive settings for unstable wifi?

Node.js keepalive settings are configuration parameters that control how long a TCP connection remains open. When working on unstable WiFi, connections often “hang” or drop silently without notifying the application.

By default, Node.js might not send packets frequently enough to detect that a WiFi signal has dipped. Keepalive settings force the runtime to send periodic “heartbeat” packets to ensure the link is still active.

For developers, tuning these settings is crucial to avoid “EPIPE” or “ECONNRESET” errors. It ensures that the client and server stay synchronized even when the physical layer experiences intermittent interference.

Step-by-Step Solutions

1. Configuring the HTTP Agent

The most effective way to manage keepalive is through the http.Agent or https.Agent. This manages a pool of sockets and keeps them warm.


const http = require('http');

const agent = new http.Agent({
  keepAlive: true,
  keepAliveMsecs: 1000 // Send TCP Keep-Alive packets every 1 second
});

http.get({
  hostname: 'example.com',
  agent: agent
}, (res) => {
  // Handle response
});

2. Setting Socket Timeouts

Unstable WiFi often results in packets being lost. You must set a socket timeout to ensure your application doesn’t wait forever for a response that will never come.


const request = http.get('http://example.com', (res) => {
  res.on('data', (chunk) => {
    // Process data
  });
});

request.on('socket', (socket) => {
  socket.setTimeout(10000); // 10 seconds timeout
  socket.on('timeout', () => {
    request.destroy();
    console.log('WiFi connection too slow, request aborted.');
  });
});

3. Implementing TCP Keep-Alive at Socket Level

For raw TCP connections (Net module), you can enable keepalive directly on the socket. This is particularly useful for WebSockets or persistent database connections over shaky WiFi.


const net = require('net');

const client = net.createConnection({ port: 8080 }, () => {
  client.setKeepAlive(true, 5000); // Enable keepalive with 5s delay
});

4. Global Agent Override

If you are using third-party libraries like Axios or Node-Fetch, you might want to set the global agent. This ensures all outgoing traffic benefits from the same stability settings.


const http = require('http');
const https = require('https');

http.globalAgent = new http.Agent({ keepAlive: true });
https.globalAgent = new https.Agent({ keepAlive: true });