Kar started this conversation 3 months ago.
Node.js error: ECONNRESET / “socket hang up” when making HTTP request
In my Node.js application, I repeatedly encounter this error when making HTTP/HTTPS requests: Error: socket hang up code: 'ECONNRESET' This happens unexpectedly—sometimes with large payloads or multiple requests. Why does it occur, and how can I fix it?
Digiaru
Posted 3 months ago
This error indicates that the other side of the TCP connection abruptly closed the socket. Frequently triggered by: • not calling req.end() on client requests, • sending oversized payloads, • using wrong modules (e.g. http instead of https), • server timeouts or premature disconnections, • or network instability Runebook+15Stack Overflow+15Stack Overflow+15Stack Overflow+3Bobby Hadz+3Stack Overflow+3Stack Overflow+1Stack Overflow+1Stack Overflow. 🔍 Common Causes: • Missing req.end() on outgoing requests results in no proper termination, causing a hang-up Bobby HadzStack Overflow. • Mixing protocol modules incorrectly, e.g. using http for an HTTPS request or wrong port Bobby HadzStack Overflow. • Large request payloads that exceed server limits or timeouts triggering abrupt closure codereadability.com+15Stack Overflow+15Stack Overflow+15. • Server-side crashes, overloads, or client-side cancellations (e.g. browser navigation or refresh) causing socket reset Stack OverflowStack Overflow.
🛠️ How to Fix It Fix Description req.end() Always call req.end() on outgoing http.request(...) or https.request(...). Omitting it prevents the request from completing Stack Overflow+3Bobby Hadz+3Stack Overflow+3.
Protocol & Port Matching Use https module with port 443, and http module with port 80. Using the wrong one often results in a socket hang-up Stack OverflowBobby Hadz.
Reduce Payload Size Split large payloads into chunks or batch requests to avoid triggering server-side resets Stack OverflowSquash.
Set Timeouts & Keep Alive Use req.setTimeout(), and set Connection: 'keep-alive' or agent options to maintain stability on repeated requests SquashBobby Hadz.
Gracefully Handle Errors Always listen to .on('error', …) on client and server sockets to prevent uncaught exceptions Stack OverflowBobby Hadz.
Retry Logic Implement retry/backoff logic for transient connection failures SquashStack Overflow.
🧩 Example Fix js CopyEdit import https from 'https';
const options = { host: 'api.example.com', path: '/data', port: 443, method: 'GET', headers: { Connection: 'keep-alive' } };
const req = https.request(options, (res) => { console.log('Status:', res.statusCode); });
req.on('error', err => { console.error('Request error:', err.code); });
// Explicitly end the request req.end(); And for Axios: js CopyEdit import axios from 'axios';
async function fetchData() { try { const response = await axios.get('https://api.example.com/data', { timeout: 5000, httpsAgent: new https.Agent({ keepAlive: true }) }); return response.data; } catch (err) { if (err.code === 'ECONNRESET' || err.code === 'ECONNABORTED') { console.error('Connection error:', err.code); // retry logic... } else { throw err; } } }
👀 TL;DR The ECONNRESET / socket hang up error occurs when the peer closes the TCP connection prematurely—often due to missing req.end(), wrong protocol/module, large payloads, or server timeouts. Fixes include properly ending requests, matching protocol and port, handling errors, and adding retry/timeouts.
🧷 Tags for Posting nodejs, http, https, socket, ECONNRESET, socket-hang-up, axios, error-handling, networking