Socket has been closed
Production Risk
Common in async servers; always check socket state or guard writes with a closed flag.
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.
- 1Reading from or writing to a socket after socket.destroy() or socket.end() + finish
- 2Using a socket reference after it has emitted the close event
- 3Async handler operating on a socket that was closed by a timeout
Triggered when an operation is attempted on a socket that has emitted the close event.
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
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.
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_CLOSEDtry {
// 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
}
}// Validate inputs before calling the operation
function safe_err_socket_closed(...args) {
// validate args here
return performOperation(...args)
}✕ Write to a socket in its close event handler
The socket is already closed at this point; writes are impossible.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev