Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

DataCloneError: a Promise could not be cloned in Node.js

ErrorDataCloneError: #<Promise> could not be cloned.

Short answer

A Promise cannot be copied between threads. postMessage, workerData and structuredClone all use the structured clone algorithm, which has no support for promises. Somewhere in the data there is a pending promise instead of its result. Find it, await it, and send the resolved plain values.

  • Applies to Node.js 22, Node.js 24, worker_threads
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Walk the data you are about to send and print the path of every promise in it. The path tells you which of the causes below applies.

    // find-promises.js
    function findPromises(value, path = 'data', seen = new Set()) {
      if (value instanceof Promise) {
        console.log('Promise at', path);
      } else if (value && typeof value === 'object' && !seen.has(value)) {
        seen.add(value);
        for (const [key, item] of Object.entries(value)) {
          findPromises(item, `${path}.${key}`, seen);
        }
      }
    }
    // call it right before the failing postMessage / new Worker / structuredClone
    findPromises(message);
  2. 2Match what you see, then jump to its fix

    1. 1The first_step prints a path of just 'data': the whole message is a promise.An async function's result was posted without awaitFix
    2. 2The first_step prints a path such as data.user or data.items.0.total.A promise sits inside the object you sendFix
    3. 3The error is thrown by new Worker(...) or by a structuredClone() call, before any message handler runs.workerData or structuredClone() receives an object holding a promiseFix

What does the error look like?

  • DataCloneError: #<Promise> could not be cloned.
  • DataCloneError thrown by worker.postMessage(), parentPort.postMessage() or structuredClone()

Cause 1 of 3

An async function's result was posted without await

1Check

Look for a postMessage call whose argument is a call to an async function, or to anything that returns a promise. The call returns the promise at once, and the clone step sees a promise instead of the value.

grep -rn "postMessage(" src/ --include=*.js

2Fix

Await the result first, inside an async function, and post the resolved value.

// worker.js
const { parentPort } = require('node:worker_threads');

parentPort.on('message', async (job) => {
  const result = await runJob(job); // runJob is async
  parentPort.postMessage(result);
});

3Verify

Post a job from the main thread and print what comes back.

node main.js

Confirmed by nodejs.org

Did this fix it?

Cause 2 of 3

A promise sits inside the object you send

1Check

The structured clone algorithm copies plain data and supports a fixed list of types, and promises are not in that list. An object with one lazy property (a query started but not awaited, or an instance that stores a pending lookup) fails as a whole.

grep -rn "Promise\|async" src/ --include=*.js | head -30

2Fix

Resolve every promise first and build a plain object from the results. Do not send class instances: only plain objects are copied, and the prototype chain is dropped.

const [user, orders] = await Promise.all([
  loadUser(id),
  loadOrders(id),
]);

worker.postMessage({
  user: { id: user.id, name: user.name },
  orders: orders.map((o) => ({ id: o.id, total: o.total })),
});

3Verify

Run findPromises on the new message. It prints nothing, and the worker receives the object.

node find-promises.js

Confirmed by developer.mozilla.org

Did this fix it?

Cause 3 of 3

workerData or structuredClone() receives an object holding a promise

1Check

The workerData option is cloned as if by postMessage(), and structuredClone() throws DataCloneError when any part of the input cannot be serialized. A config object that was assembled with unresolved promises fails here the same way.

grep -rn "workerData\|structuredClone(" src/ --include=*.js

2Fix

Await the values before you create the Worker, or before you call structuredClone(), and pass only the resolved data.

const { Worker } = require('node:worker_threads');

async function start() {
  const config = await loadConfig(); // not: loadConfig()
  return new Worker('./worker.js', { workerData: { config } });
}

3Verify

The worker starts and reads the same values from workerData.

// worker.js
const { workerData } = require('node:worker_threads');
console.log(workerData);

Confirmed by developer.mozilla.org

Did this fix it?

How do I stop it coming back?

  • Type the message shape (a TypeScript interface of plain fields) so a Promise<T> cannot be assigned where T is expected.
  • Turn on a linter rule against floating (un-awaited) promises, so a missing await is flagged before it runs.
  • Send small plain objects with ids and numbers, and rebuild rich objects on the receiving side.
  • Write one findPromises-style test for each message type the worker accepts.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

ng serve says it cannot determine the project or target

Cannot determine project for command.

The Angular CLI looked through angular.json for a project that defines the target you asked for (serve, build, test) and found none, or found several and could not pick one.

3 causes, each with a fix

Back end

ng serve cannot find the dev-server builder package

Could not find the implementation for builder @angular/build:dev-server

The builder named in angular.json (for example @angular-devkit/build-angular:dev-server) is looked up as an npm package starting from the workspace root.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.