Socket Hang Up: What It Means and How to Fix It
Error reference
Socket Hang Up
Language
Severity
HighWhen it happens
The 'socket hang up' error occurs in Node.js when an HTTP connection is closed by the server before a complete response is received.
Potential fixes
Always attach an 'error' event handler to Node.js HTTP requests. Implement retry logic for idempotent requests. Check server-side logs to determine why the connection is being closed early. Increase proxy timeout settings if the server needs more processing time.
Related errors
Deep dive
The 'socket hang up' error occurs in Node.js when an HTTP connection is closed by the server before a complete response is received. It is closely related to ECONNRESET and typically means the server closed the socket prematurely.
Why it happens
- •The server closes the connection before finishing the response body.
- •A reverse proxy (nginx, load balancer) times out and terminates the connection.
- •The server crashes while processing the request.
- •Not draining the request body on the server side causes the client to time out.
Potential fixes
Always attach an 'error' event handler to Node.js HTTP requests. Implement retry logic for idempotent requests. Check server-side logs to determine why the connection is being closed early. Increase proxy timeout settings if the server needs more processing time.
Examples
Code that triggers the error
const http = require("http");
const req = http.get("http://example.com/api", (res) => {
res.resume();
});
req.end();
// Server closes connection before sending full responseError output
Error: socket hang up
code: 'ECONNRESET'Fixed code
const http = require("http");
const req = http.get("http://example.com/api", (res) => {
let body = "";
res.on("data", (chunk) => { body += chunk; });
res.on("end", () => console.log(body));
});
req.on("error", (err) => {
console.error("Request failed:", err.message);
});Practice in English
How would you explain a Socket Hang Up to a fellow dev? Choose the right phrase:
"I hit an error...
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free