ERR_SOCKET_ALREADY_CONNECTED
Node.jsERRORNotableNetworkHIGH confidence

Socket is already connected

Production Risk

Low — caught immediately at call site; track socket state in connection managers.

What this means

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.

Why it happens
  1. 1Calling socket.connect() twice on the same socket without closing it first
  2. 2Logic error where connect() is called in a loop without checking connection state
  3. 3Race condition in async code where two code paths both call connect()
How to reproduce

Triggered when connect() is called on a net.Socket that is already connected.

trigger — this will error
trigger — this will error
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

Check socket state before connecting
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

Create a new socket for each connection
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.

Code examples
Triggerjs
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_CONNECTED
Handle in try/catchjs
try {
  // 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
  }
}
Defensive pattern to avoid itjs
// Validate inputs before calling the operation
function safe_err_socket_already_connected(...args) {
  // validate args here
  return performOperation(...args)
}
What not to do

Call connect() on an already-connected socket

A socket can only be connected to one peer at a time.

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