/errors/http/socket-hang-up-econnreset
Error: socket hang up (ECONNRESET) in Node.js HTTP requests
- tool
- HTTP
- versions
- Node.js 18+
- os
- any
Error: socket hang up (code ECONNRESET) means Node.js sent an HTTP request and the connection was closed before any response arrived. The TCP connection itself worked, so this is not ECONNREFUSED: the server, a proxy or a load balancer accepted the request and then hung up. Look at the server side first; when the error is intermittent, a keep-alive timeout mismatch is the usual cause.
Reproduce it
A local server that destroys the socket without answering:
cat > hangup.js <<'EOF'
const http = require("http");
const srv = http.createServer((req, res) => req.socket.destroy());
srv.listen(4920, "127.0.0.1", () => {
http.get("http://127.0.0.1:4920/", () => {}).on("error", (e) => {
console.log(`${e.name}: ${e.message}`, `(code ${e.code})`);
srv.close();
});
});
EOF
node hangup.jsOutput
Error: socket hang up (code ECONNRESET)
If the server had sent a status line and then closed the connection in the middle of the body, the error would be aborted on the response instead. socket hang up specifically means nothing was received.
Intermittent errors and keep-alive
Since Node.js 19 the default HTTP agent keeps connections alive. If the server closes an idle connection at the same moment the client reuses it, the request fails with socket hang up. Node.js servers close idle keep-alive connections after server.keepAliveTimeout (5 seconds by default); proxies and load balancers have their own idle timeouts.
| Fix | How |
|---|---|
| Longer server idle timeout | Set server.keepAliveTimeout (and the proxy idle timeout) above the client idle time |
| Shorter client idle time | new http.Agent({ keepAlive: true, timeout: 4000 }) |
| Confirm the cause | Send the failing request with agent: false (no connection reuse) |
| Tolerate it | Retry idempotent requests once when the error occurs on a reused socket |
Libraries
- axios shows the same error as
AxiosError: socket hang upwithcode: 'ECONNRESET'. fetch()in Node.js (undici) reportsTypeError: fetch failed; the reason is inerror.cause(for exampleSocketError: other side closed).- Behind nginx, a backend that hangs up produces
upstream prematurely closed connectionin the nginx error log and a502 Bad Gatewayfor the client.