ERR_SOCKET_ALREADY_ENDED
Node.jsERRORNotableNetworkHIGH confidence

The socket has already been ended.

Production Risk

Medium. This indicates a state management issue in handling network connections. It can lead to unhandled exceptions and crashes if not properly caught, although it often just signals a failed write.

What this means

This error is thrown when an attempt is made to write data to a socket that has already been closed. Sockets can be ended by either the local side calling `.end()` or the remote side closing its connection. Once a socket is in the ended state, no more data can be sent through it.

Why it happens
  1. 1Calling `socket.write()` or `socket.end()` after the socket has already been closed.
  2. 2A race condition where one part of the code closes a socket while another part is still attempting to write to it.
  3. 3The remote client disconnects, and the server code does not properly handle the 'close' event before trying to send more data.
How to reproduce

This error occurs within the `net` or `http` modules when a write operation is initiated on a socket object that has already transitioned to a closed or ended state.

trigger — this will error
trigger — this will error
const net = require('net');
const server = net.createServer((socket) => {
  socket.end('Goodbye!');
  try {
    socket.write('One more thing...'); // Throws error
  } catch (err) {
    console.error(err.code);
  }
});
server.listen(3000);

expected output

ERR_SOCKET_ALREADY_ENDED

Fix

Check if Socket is Writable

WHEN Before writing data to a socket in a long-lived connection.

Check if Socket is Writable
function writeToSocket(socket, data) {
  if (socket.writable) {
    socket.write(data);
  } else {
    console.log('Socket is not writable, cannot send data.');
  }
}

Why this works

Before attempting to write, check the `socket.writable` property. If it is `false`, the socket has been closed or is in the process of closing, and you should not attempt to write to it.

Code examples
Triggerjs
const net = require('net');
const server = net.createServer((socket) => {
  socket.end('Goodbye!');
  try {
    socket.write('One more thing...'); // Throws error
  } catch (err) {  // this triggers ERR_SOCKET_ALREADY_ENDED
Handle in try/catchjs
try {
  // operation that may throw ERR_SOCKET_ALREADY_ENDED
  riskyOperation()
} catch (err) {
  if (err.code === 'ERR_SOCKET_ALREADY_ENDED') {
    console.error('ERR_SOCKET_ALREADY_ENDED:', err.message)
  } else {
    throw err
  }
}
Defensive pattern to avoid itjs
function safeSend(socket, data) {
  if (socket.writable) {
    socket.write(data)
  }
}
What not to do

Sources
Official documentation ↗

https://github.com/nodejs/node/blob/main/lib/net.js

More information

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

← All Node.js errors