| Issue | Primary Cause | Quick Fix |
|---|---|---|
| ECONNRESET | Sudden network drop or WiFi instability. | Implement retry logic and error listeners. |
| Socket Hang Up | Server closed connection prematurely. | Adjust keepAlive and timeout settings. |

What is a Node.js Socket Hang Up?
A “socket hang up” error in Node.js occurs when a connection is terminated unexpectedly before the response could be fully received. In the context of JavaScript WiFi drops, this usually happens when the local network interface loses its handshake with the router.
Technically, this is often identified by the ECONNRESET error code. It signifies that the other end of the socket—either the server or a proxy—has closed the connection without sending a proper TCP FIN packet.
For developers working in unstable environments, such as remote offices or mobile hotspots, these interruptions can break long-running API calls or database streams. Understanding how to handle these drops is critical for application resilience.
Step-by-Step Solutions
1. Implement Keep-Alive in HTTP Agents
By default, Node.js might not reuse connections efficiently. Using an http.Agent with keepAlive set to true helps maintain a persistent connection, reducing the overhead of constant re-handshaking during minor WiFi blips.
const http = require('http');
const agent = new http.Agent({ keepAlive: true });
http.get({
hostname: 'example.com',
port: 80,
agent: agent
}, (res) => {
// Handle response
});
2. Increase Socket Timeouts
Sometimes the socket hangs up because the network is slow rather than completely dead. Increasing the timeout value gives the connection more breathing room to recover from a momentary signal drop.
const request = http.get('http://example.com', (res) => {
// logic
});
request.on('socket', (socket) => {
socket.setTimeout(30000); // Set to 30 seconds
socket.on('timeout', () => {
request.destroy();
});
});
3. Global Error Handling for ECONNRESET
To prevent your entire Node.js process from crashing when a WiFi drop occurs, you must attach an error listener to every request. This allows you to log the event or trigger a retry instead of a total failure.
request.on('error', (err) => {
if (err.code === 'ECONNRESET') {
console.error('Socket hang up detected. Retrying...');
// Logic to restart the request
}
});
4. Use AbortController for Timeouts
In modern Node.js environments, using the AbortController with the Fetch API or http module is the cleanest way to manage hanging sockets. This ensures resources are freed as soon as the network state becomes invalid.
const controller = new AbortController();
const signal = controller.signal;
setTimeout(() => controller.abort(), 5000); // Abort after 5s
fetch('https://example.com', { signal })
.then(res => res.json())
.catch(err => {
if (err.name === 'AbortError') {
console.log('Request timed out due to network issues.');
}
});