ERR_SOCKET_CLOSED
Node.jsERRORNotableNetworkHIGH confidence

Socket has been closed

Production Risk

Common in async servers; always check socket state or guard writes with a closed flag.

What this means

Thrown when an operation is attempted on a socket that has already been closed. Once a socket is closed its file descriptor is released back to the OS; no further reads, writes, or control operations are possible.

Why it happens
  1. 1Reading from or writing to a socket after socket.destroy() or socket.end() + finish
  2. 2Using a socket reference after it has emitted the close event
  3. 3Async handler operating on a socket that was closed by a timeout
How to reproduce

Triggered when an operation is attempted on a socket that has emitted the close event.

trigger — this will error
trigger — this will error
const net = require('net');
const socket = net.createConnection({ host: 'localhost', port: 3000 }, () => {
  socket.end();
  socket.on('close', () => {
    socket.write('hello'); // throws — socket is closed
  });
});

expected output

Error [ERR_SOCKET_CLOSED]: Socket is closed

Fix

Stop all operations on close event

WHEN In connection handlers with async operations

Stop all operations on close event
socket.on('close', () => {
  // Clean up any pending operations but do NOT write to the socket
  clearTimeout(timeoutHandle);
});

Why this works

The close event is the signal to stop all socket operations; writing after it throws.

Code examples
Triggerjs
const net = require('net');
const socket = net.createConnection({ host: 'localhost', port: 3000 }, () => {
  socket.end();
  socket.on('close', () => {
    socket.write('hello'); // throws — socket is closed
  });  // this triggers ERR_SOCKET_CLOSED
Handle in try/catchjs
try {
  // operation that may throw ERR_SOCKET_CLOSED
  riskyOperation()
} catch (err) {
  if (err.code === 'ERR_SOCKET_CLOSED') {
    console.error('ERR_SOCKET_CLOSED:', err.message)
  } else {
    throw err
  }
}
Defensive pattern to avoid itjs
// Validate inputs before calling the operation
function safe_err_socket_closed(...args) {
  // validate args here
  return performOperation(...args)
}
What not to do

Write to a socket in its close event handler

The socket is already closed at this point; writes are impossible.

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