ERR_INVALID_CALLBACK
Node.jsERRORNotableAsyncHIGH confidence

Callback argument must be a function

Production Risk

Low — caught immediately; switch to promise APIs to avoid callback type issues.

What this means

Thrown when a Node.js API that requires a callback function receives a non-function value. Many Node.js core APIs use callback-style async patterns where the last argument must be a function.

Why it happens
  1. 1Passing undefined as the callback argument (e.g. missing argument)
  2. 2Passing an object or string where a callback function is expected
  3. 3Accidentally omitting the callback in a function call
How to reproduce

Triggered when a core API validates its callback argument and finds it is not a function.

trigger — this will error
trigger — this will error
const fs = require('fs');
fs.readFile('/tmp/data.txt', 'utf8', 'not-a-function'); // throws

expected output

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received type string ('not-a-function')

Fix 1

Pass a function as the callback argument

WHEN Always — check the API signature

Pass a function as the callback argument
const fs = require('fs');
fs.readFile('/tmp/data.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

Why this works

Providing a proper function satisfies the callback type check.

Fix 2

Use the promise-based API to avoid callbacks

WHEN When you prefer async/await

Use the promise-based API to avoid callbacks
const { readFile } = require('fs/promises');
const data = await readFile('/tmp/data.txt', 'utf8');

Why this works

The promise API does not require a callback argument, eliminating this class of error.

Code examples
Triggerjs
const fs = require('fs');
fs.readFile('/tmp/data.txt', 'utf8', 'not-a-function'); // throws  // this triggers ERR_INVALID_CALLBACK
Handle in try/catchjs
try {
  // operation that may throw ERR_INVALID_CALLBACK
  riskyOperation()
} catch (err) {
  if (err.code === 'ERR_INVALID_CALLBACK') {
    console.error('ERR_INVALID_CALLBACK:', err.message)
  } else {
    throw err
  }
}
Defensive pattern to avoid itjs
// Validate inputs before calling the operation
function safe_err_invalid_callback(...args) {
  // validate args here
  return performOperation(...args)
}
What not to do

Pass non-function values as callbacks to async Node.js APIs

The callback is invoked asynchronously; a non-function value causes an immediate type error.

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