Socket is already connected
Production Risk
Low — caught immediately at call site; track socket state in connection managers.
Thrown when a connection attempt is made on a socket that is already in a connected state. Each socket can only maintain one connection at a time; attempting to connect an already-connected socket is an error.
- 1Calling socket.connect() twice on the same socket without closing it first
- 2Logic error where connect() is called in a loop without checking connection state
- 3Race condition in async code where two code paths both call connect()
Triggered when connect() is called on a net.Socket that is already connected.
const net = require('net');
const socket = net.createConnection({ host: 'localhost', port: 3000 }, () => {
socket.connect({ host: 'localhost', port: 3001 }); // already connected — throws
});expected output
Error [ERR_SOCKET_ALREADY_CONNECTED]: Socket is already connected
Fix 1
Check socket state before connecting
WHEN When connection logic may be called multiple times
if (!socket.connecting && !socket.destroyed && socket.readyState !== 'open') {
socket.connect({ host, port });
}Why this works
Checking socket state prevents redundant connect() calls.
Fix 2
Create a new socket for each connection
WHEN When you need to connect to a different host
const socket1 = net.createConnection({ host: 'host1', port: 3000 });
const socket2 = net.createConnection({ host: 'host2', port: 3001 });Why this works
Each socket maintains one connection; create separate sockets for separate connections.
const net = require('net');
const socket = net.createConnection({ host: 'localhost', port: 3000 }, () => {
socket.connect({ host: 'localhost', port: 3001 }); // already connected — throws
}); // this triggers ERR_SOCKET_ALREADY_CONNECTEDtry {
// operation that may throw ERR_SOCKET_ALREADY_CONNECTED
riskyOperation()
} catch (err) {
if (err.code === 'ERR_SOCKET_ALREADY_CONNECTED') {
console.error('ERR_SOCKET_ALREADY_CONNECTED:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_socket_already_connected(...args) {
// validate args here
return performOperation(...args)
}✕ Call connect() on an already-connected socket
A socket can only be connected to one peer at a time.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev