日本語

How to Fix “socket hang up” in Node.js

​​Node.js​JavaScript,Troubleshooting

When http.request in Node.js fails with Error: socket hang up (code ECONNRESET), the connection was closed before a response came back. Start by checking the logs of the server you connected to to see what happened there. With fetch() in the same situation, the message is TypeError: fetch failed, and its cause shows other side closed.

This applies when a Node.js script or an API server sends an HTTP request to another API server and stops with this error. In a test environment, I built a server that crashes when it receives invalid JSON, triggered the error, and confirmed that fixing the server removes it.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.5, and curl 8.5.0. The client and server both ran on the same machine. I did not test HTTPS, setups with a proxy or load balancer in between, cases where a keep-alive connection is reused and then closed, Windows, macOS, or Node.js 21 and earlier.

The message you get when the server crashes

For the test, I wrote a server, server.mjs, that runs JSON.parse on the request body and returns the result. If the body is not valid JSON, JSON.parse throws, and since nothing catches the error, the whole process exits.

js
import { createServer } from 'node:http';

const server = createServer((req, res) => {
  let body = '';
  req.on('data', (chunk) => { body += chunk; });
  req.on('end', () => {
    const data = JSON.parse(body);
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ received: data }));
  });
});

server.listen(3000, () => {
  console.log('http://localhost:3000 で待ち受けています');
});

The client, client-http.mjs, uses request from node:http to POST JSON with a trailing comma.

js
import { request } from 'node:http';

const req = request('http://localhost:3000/api/items', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
}, (res) => {
  let text = '';
  res.on('data', (chunk) => { text += chunk; });
  res.on('end', () => console.log(res.statusCode, text));
});
req.end('{"name": "neko",}');

With the server running, I ran node client-http.mjs. It printed the following and exited with code 1.

text
node:events:497
      throw er; // Unhandled 'error' event
      ^

Error: socket hang up
    at Socket.socketOnEnd (node:_http_client:599:25)
    at Socket.emit (node:events:531:35)
    at endReadableNT (node:internal/streams/readable:1698:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:89:21)
Emitted 'error' event on ClientRequest instance at:
    at emitErrorEvent (node:_http_client:108:11)
    at Socket.socketOnEnd (node:_http_client:599:5)
    at Socket.emit (node:events:531:35)
    at endReadableNT (node:internal/streams/readable:1698:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:89:21) {
  code: 'ECONNRESET'
}

Node.js v22.23.5

The Node.js documentation for http.request says that if the connection is closed partway through before a response is received, an 'error' event fires with the message Error: socket hang up and the code ECONNRESET. The output above matches this.

The first line, Unhandled 'error' event, shows that no 'error' listener is attached to req. According to the events documentation, when an 'error' event fires with no listener, Node.js throws the error, prints the stack trace, and exits the process. This is why the client script stopped.

With fetch, the error says "other side closed"

I also tried client-fetch.mjs, which sends the same body to the same server using fetch().

js
const res = await fetch('http://localhost:3000/api/items', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: '{"name": "neko",}',
});
console.log(res.status, await res.text());

This time, the words socket hang up did not appear. Instead, the [cause] under TypeError: fetch failed showed SocketError: other side closed. The exit code was 1. (The paths are replaced with example values.)

text
node:internal/deps/undici/undici:15456
      Error.captureStackTrace(err);
            ^

TypeError: fetch failed
    at node:internal/deps/undici/undici:15456:13
    at async file:///path/to/app/client-fetch.mjs:1:13 {
  [cause]: SocketError: other side closed
      at Socket.<anonymous> (node:internal/deps/undici/undici:6569:28)
      at Socket.emit (node:events:531:35)
      at endReadableNT (node:internal/streams/readable:1698:12)
      at process.processTicksAndRejections (node:internal/process/task_queues:89:21) {
    code: 'UND_ERR_SOCKET',
    socket: {
      localAddress: '127.0.0.1',
      localPort: 42962,
      remoteAddress: '127.0.0.1',
      remotePort: 3000,
      remoteFamily: 'IPv4',
      timeout: undefined,
      bytesWritten: 248,
      bytesRead: 0
    },
    [Symbol(undici.error.UND_ERR)]: true,
    [Symbol(undici.error.UND_ERR_SOCKET)]: true
  }
}

Node.js v22.23.5

Node.js's fetch is built on undici, an HTTP client, not on node:http (Node.js documentation for fetch). That is why the same cause produces different wording. In the socket details, bytesRead: 0 means that zero bytes were received from the server (net documentation for socket.bytesRead). The connection was closed before even one byte of the response arrived.

The cause is in the server log

The client error only tells you that the connection was closed. To find out why, you have to look at the server. In my test, the server output contained the following stack trace, and the server process exited with code 1. (The paths are replaced with example values.)

text
http://localhost:3000 で待ち受けています
<anonymous_script>:1
{"name": "neko",}
                ^

SyntaxError: Expected double-quoted property name in JSON at position 16 (line 1 column 17)
    at JSON.parse (<anonymous>)
    at IncomingMessage.<anonymous> (file:///path/to/app/server.mjs:7:23)
    at IncomingMessage.emit (node:events:519:28)
    at endReadableNT (node:internal/streams/readable:1698:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:89:21)

Node.js v22.23.5

JSON.parse on line 7 of server.mjs fails at the comma after neko". As the process documentation describes, an exception that is not caught prints a stack trace and terminates the process. Once the process exits, its connections are closed too, so the waiting client sees socket hang up.

Sending the same body with curl, which bypasses Node.js entirely, also got no response.

console
$ curl -sS -X POST -H 'Content-Type: application/json' -d '{"name": "neko",}' http://localhost:3000/api/items
curl: (52) Empty reply from server

In the libcurl error code list, error 52 means the server returned nothing. Since curl shows the same result, you can narrow it down: the connection was closed on the server side, not by the client code.

Catch the exception on the server and return an error response

The fix belongs on the server. I wrapped JSON.parse in try/catch so that a parse failure returns a 400 response instead of crashing the process (server-fixed.mjs).

js
import { createServer } from 'node:http';

const server = createServer((req, res) => {
  let body = '';
  req.on('data', (chunk) => { body += chunk; });
  req.on('end', () => {
    let data;
    try {
      data = JSON.parse(body);
    } catch {
      res.statusCode = 400;
      res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify({ error: 'JSON の形が正しくありません' }));
      return;
    }
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ received: data }));
  });
});

server.listen(3000, () => {
  console.log('http://localhost:3000 で待ち受けています');
});

I ran the same client-http.mjs and client-fetch.mjs against this server. Neither showed an error. Each printed the 400 response and exited with code 0.

console
$ node client-http.mjs
400 {"error":"JSON の形が正しくありません"}
$ node client-fetch.mjs
400 {"error":"JSON の形が正しくありません"}

The server printed only the one line at startup, and it kept running after I ran the clients.

Also handle the error on the client

Sometimes the server belongs to someone else and you can't fix it. Even then, you can keep the script from stopping with a long stack trace by attaching an 'error' listener to req (client-http-handled.mjs).

js
import { request } from 'node:http';

const req = request('http://localhost:3000/api/items', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
}, (res) => {
  let text = '';
  res.on('data', (chunk) => { text += chunk; });
  res.on('end', () => console.log(res.statusCode, text));
});
req.on('error', (err) => {
  console.error(`リクエストに失敗しました: ${err.message}(${err.code})`);
  process.exitCode = 1;
});
req.end('{"name": "neko",}');

When I sent the request to the failing server (server.mjs), it printed one line and exited with code 1.

console
$ node client-http-handled.mjs
リクエストに失敗しました: socket hang up(ECONNRESET)

When I sent it to the fixed server, it printed 400 {"error":"JSON の形が正しくありません"} and exited with code 0.

The same message appears when your own code times out

Sometimes the connection is closed by your own code, not by the other side. The timeout option of http.request only emits a 'timeout' event after the given time passes with no activity. You still have to stop the request yourself (documentation for the 'timeout' event of http.request). If you call req.destroy() at that point, the connection is closed before the response arrives, and socket hang up appears again.

I ran the following client-timeout.mjs, which times out after 1 second, against a server that responds after 3 seconds (server-slow.mjs).

js
import { request } from 'node:http';

const req = request('http://localhost:3000/', { timeout: 1000 }, (res) => {
  res.resume();
  res.on('end', () => console.log(res.statusCode));
});
req.on('timeout', () => {
  req.destroy();
});
req.on('error', (err) => {
  console.error(`${err.message}(code: ${err.code ?? "なし"})`);
});
req.end();
console
$ node client-timeout.mjs
socket hang up(code: ECONNRESET)

From this message alone, you cannot tell whether the other side closed the connection or your code aborted it. The http.request documentation says that if req.destroy() is called before the connection is established, the 'error' event receives either socket hang up or the error passed to req.destroy(). For this case, where the request is aborted while waiting for a response, I changed the 'timeout' listener as follows. The error message I passed was shown instead of socket hang up.

js
req.on('timeout', () => {
  req.destroy(new Error('1秒以内に応答がなかったので打ち切りました'));
});
console
$ node client-timeout-fixed.mjs
1秒以内に応答がなかったので打ち切りました(code: なし)

To time out a fetch request, pass AbortSignal.timeout() as the signal. I ran fetch('http://localhost:3000/', { signal: AbortSignal.timeout(1000) }) against the same server and printed the error from catch with console.error(`${err.name}: ${err.message}`). The output was:

text
TimeoutError: The operation was aborted due to timeout

The name is TimeoutError, so you can tell it apart from a dropped connection (MDN documentation for AbortSignal.timeout()).

​Posted by 86