ERR_USE_AFTER_CLOSE node streams ai_generated true

Error [ERR_USE_AFTER_CLOSE]: This socket has been ended by the other party

ID: node/err-use-after-close

Also available as: JSON · Markdown
91%Fix Rate
93%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
20 active

Root Cause

Attempting to write to a socket or stream that has already been closed.

generic

Workarounds

  1. 90% success Check socket.destroyed before writing
    if (!socket.destroyed) socket.write(data)
  2. 93% success Handle the 'close' and 'end' events to stop writing
    socket.on('close', () => { /* stop sending */ })

    Sources: https://nodejs.org/api/net.html#class-netsocket

Dead Ends

Common approaches that don't work:

  1. Wrapping every write in try/catch 65% fail

    Masks the lifecycle management bug

  2. Keeping a global reference to prevent garbage collection 80% fail

    Socket is closed by the remote; keeping a reference doesn't reopen it

Error Chain

Frequently confused with: