ERR_USE_AFTER_CLOSE
Node.jsERRORNotableGeneralHIGH confidence

An operation was attempted on a resource that has been closed.

Production Risk

Medium. This indicates a state management problem that could lead to unexpected crashes or resource leaks if not handled correctly.

What this means

This error is thrown when an attempt is made to use a resource after its `close()` method has been called. This is common with resources that manage an underlying handle, like a file descriptor or a network socket. Once closed, the resource is no longer usable, and any further operations are invalid.

Why it happens
  1. 1Attempting to interact with an `fs.FSWatcher` after calling its `.close()` method.
  2. 2Using an HTTP/2 session or stream object after it has been closed.
  3. 3A race condition where one part of the code closes a resource while another part is about to use it.
How to reproduce

This error occurs when a method is called on an object that has an internal 'closed' state flag set to true.

trigger — this will error
trigger — this will error
const fs = require('fs');
const watcher = fs.watch(__filename);

watcher.close();

try {
  // Attempting to add another listener after closing.
  watcher.on('change', () => {});
} catch (err) {
  console.error(err.code);
}

expected output

ERR_USE_AFTER_CLOSE

Fix

Ensure Resource is Open

WHEN Interacting with a closeable resource.

Ensure Resource is Open
const fs = require('fs');
const watcher = fs.watch(__filename);
let isClosed = false;

watcher.on('close', () => {
  isClosed = true;
});

// Sometime later...
if (!isClosed) {
  // It's safe to interact with the watcher.
}

Why this works

Structure your code to ensure that operations on a resource only happen between its creation and the emission of its 'close' event. Avoid sharing closeable resources across complex asynchronous flows where their state is uncertain.

Code examples
Triggerjs
const fs = require('fs');
const watcher = fs.watch(__filename);

watcher.close();

try {  // this triggers ERR_USE_AFTER_CLOSE
Handle in try/catchjs
try {
  // operation that may throw ERR_USE_AFTER_CLOSE
  riskyOperation()
} catch (err) {
  if (err.code === 'ERR_USE_AFTER_CLOSE') {
    console.error('ERR_USE_AFTER_CLOSE:', err.message)
  } else {
    throw err
  }
}
Defensive pattern to avoid itjs
// Validate inputs before calling the operation
function safe_err_use_after_close(...args) {
  // validate args here
  return performOperation(...args)
}
What not to do

Same error in other languages

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

← All Node.js errors