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.
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.
- 1socket.destroy() called immediately after socket.connect() before the handshake completes
- 2A race condition where a timeout handler destroys the socket concurrently with connection setup
- 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
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
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.
const net = require('net');
const socket = new net.Socket();
socket.destroy();
socket.connect(3000, '127.0.0.1');
// TypeError [ERR_SOCKET_CLOSED_BEFORE_CONNECTION]✕ 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.
ERR_SOCKET_CLOSED_BEFORE_CONNECTION was added to provide a specific error code for the destroy-before-connect race condition.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev