ERR_SOCKET_CLOSED_BEFORE_CONNECTION
Node.jsERRORNotableNetwork

Socket was destroyed before connection was established

Quick Answer

Only destroy or end a socket after the 'connect' event fires, or check socket.connecting and socket.destroyed before writing.

Production Risk

Medium — indicates a race condition in socket lifecycle management.

What this means

Thrown when socket.destroy() or socket.end() is called before the TCP handshake completes. Added in Node.js 18.14 / 20.0 to give a specific error for this timing condition that previously produced a generic socket error.

Why it happens
  1. 1socket.destroy() called immediately after socket.connect() before the handshake completes
  2. 2A race condition where a timeout handler destroys the socket concurrently with connection setup
  3. 3Calling socket.write() on a socket that was destroyed in the same tick

Fix 1

Wait for connect event before operating on the socket

WHEN When manually managing TCP sockets

Wait for connect event before operating on the socket
const net = require('net');
const socket = new net.Socket();

socket.connect(3000, '127.0.0.1', () => {
  // ✓ Only operate on the socket after 'connect' fires
  socket.write('hello');
  socket.end();
});

socket.on('error', (err) => {
  console.error('Socket error:', err.message);
});

Why this works

The 'connect' callback runs after the TCP handshake succeeds — any operations inside are guaranteed to have an established connection.

Fix 2

Guard with socket.connecting and socket.destroyed

WHEN When the socket lifecycle is managed across async boundaries

Guard with socket.connecting and socket.destroyed
function safeSend(socket, data) {
  if (socket.destroyed || socket.connecting) {
    throw new Error('Socket not ready');
  }
  socket.write(data);
}

Why this works

socket.connecting is true during the handshake; socket.destroyed is true after destroy() is called. Both guards prevent writes to an unusable socket.

Code examples
Triggerjs
const net = require('net');
const socket = new net.Socket();
socket.destroy();
socket.connect(3000, '127.0.0.1');
// TypeError [ERR_SOCKET_CLOSED_BEFORE_CONNECTION]
What not to do

Call socket.destroy() in a timeout that races with socket.connect()

If the timeout fires before the connect callback, the socket is destroyed mid-handshake, producing ERR_SOCKET_CLOSED_BEFORE_CONNECTION.

Same error in other languages
Version notes
Node.js 18.14 / 20.0

ERR_SOCKET_CLOSED_BEFORE_CONNECTION was added to provide a specific error code for the destroy-before-connect race condition.

Sources
Official documentation ↗

Node.js Error Codes Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Node.js errors