Sub topic 7
Functions, DOM Nodes and DataCloneError
This chapter assumes you already know how structuredClone copies plain objects, arrays, Date, Map and Set, and that you are comfortable with try/catch. The examples run in Node.js 17 or later or in a browser console. The DOM example needs a browser.
Earlier chapters showed values that structuredClone copies correctly. This chapter covers values it refuses to copy. A JSON round-trip quietly drops a function. structuredClone stops instead and throws a DOMException named DataCloneError. You need to know which values trigger that error, what the error looks like, and how to find and fix the value that caused it.
Why structuredClone Refuses Instead of Skipping
The structured clone algorithm builds a copy that is independent of the original and of the code that created it. Some values cannot be separated from their surroundings:
- A function closes over variables in the scope where it was defined. Copying its source text would not copy those variables, so the algorithm cannot produce a correct copy.
- A DOM node belongs to one document and one rendering engine. A detached copy of its JavaScript wrapper would mean nothing.
- A
WeakMap, aPromiseor aProxyholds internal state that the algorithm has no way to read.
The algorithm has two options for these values. It could drop them silently, as JSON.stringify drops functions and undefined, or it could fail. It fails. That makes the copy harder to make, but you never get back a copy with a missing piece you didn't notice.
try {
structuredClone({ onClick: () => {} });
} catch (err) {
console.log(err.name); // 'DataCloneError'
}What Throws and What Does Not
The table lists common values that throw, plus some that look like they would throw but don't.
| Value | Result | Notes |
|---|---|---|
| Function or arrow function | Throws `DataCloneError` | Applies at any nesting depth, including inside a `Map` or `Set` |
| Class constructor | Throws `DataCloneError` | A class is a function |
| Symbol primitive, such as `Symbol('id')` | Throws `DataCloneError` | Applies as a top-level value or as a property value |
| DOM node (`Element`, `Text`, `Document`) | Throws `DataCloneError` | Browser only |
| `Window`, most other platform objects | Throws `DataCloneError` | Some platform objects are allowed, see below |
| `WeakMap`, `WeakSet`, `WeakRef` | Throws `DataCloneError` | Their contents cannot be listed |
| `Promise` | Throws `DataCloneError` | It has internal state the algorithm cannot copy |
| `Proxy` | Throws `DataCloneError` | Even a proxy around a plain object |
| `Error`, `TypeError`, `RangeError` and similar | Copied | `name` and `message` survive, and modern runtimes also keep `stack` and `cause` |
| `Blob`, `File`, `ImageData`, `CryptoKey` | Copied | These are serializable platform objects |
| Method defined in a class body | Ignored | It lives on the prototype, which is never walked |
The last row needs a closer look. The algorithm copies only own enumerable properties, so a method on a class prototype is never visited and causes no error. A function stored as an own property is visited, and it throws. That includes a method bound in the constructor or a class field holding an arrow function.
class Counter {
count = 0;
increment() { this.count++; } // on the prototype: ignored
}
class BoundCounter {
count = 0;
increment = () => { this.count++; }; // own property: visited
}
console.log(structuredClone(new Counter())); // { count: 0 }
try {
structuredClone(new BoundCounter());
} catch (err) {
console.log(err.name); // 'DataCloneError'
}The two classes behave the same when you call their methods, but only the first can be cloned. If your codebase binds methods with class fields, expect DataCloneError wherever those instances get cloned.
Anatomy of the Error
DataCloneError is not a separate class. It is a DOMException whose name property is 'DataCloneError'. Node.js has provided DOMException as a global since version 17, so the same check works in browsers and in Node.
try {
structuredClone({ id: Symbol('id') });
} catch (err) {
console.log(err instanceof DOMException); // true
console.log(err instanceof TypeError); // false
console.log(err.name); // 'DataCloneError'
console.log(err.code); // 25 (legacy DATA_CLONE_ERR code)
console.log(typeof err.message); // 'string'
}Base your checks on err.name. The text of err.message varies between engines and versions. It usually quotes the offending value, such as () => {} could not be cloned, but it does not tell you where in the structure that value was. In a large object that can make the error hard to trace. A tool for finding the location appears later in this chapter.
The operation is all-or-nothing
One bad value anywhere in the graph makes the whole call throw. You get no partial copy. Values the algorithm visited before the bad one are thrown away.
Throwing does not mean nothing ran, though. The algorithm reads properties in order, and reading an accessor property runs its getter. Any getter reached before the failure has already run, along with its side effects.
let reads = 0;
const source = {
get first() { reads++; return 'ok'; },
second: () => {}
};
try {
structuredClone(source);
} catch (err) {
console.log(err.name); // 'DataCloneError'
}
console.log(reads); // 1: the getter ran before the failureErrors that are not DataCloneError
Not every exception from structuredClone is a DataCloneError. If a getter throws, its exception passes through unchanged. A broad catch that treats every failure as "not cloneable" will hide real bugs, so check the name and rethrow anything else.
const source = {
get config() { throw new RangeError('config not loaded'); }
};
try {
structuredClone(source);
} catch (err) {
console.log(err.name); // 'RangeError'
console.log(err.message); // 'config not loaded'
}The diagram shows how the algorithm handles each value it meets and where the two kinds of exception come from.
DOM Nodes
In a browser, cloning any DOM node throws:
// Browser console only
try {
structuredClone(document.body);
} catch (err) {
console.log(err.name); // 'DataCloneError'
}This usually happens by accident. State objects end up holding a reference to an element ({ anchor: buttonEl, open: true }), or an event object gets stored and cloned later. Event objects are not cloneable either, and their target property is a node.
There are three fixes, depending on what you actually need:
- To copy the element inside the document, use
node.cloneNode(true). It copies the subtree but not listeners added withaddEventListener. - To copy the element's markup as data, store
element.outerHTMLor a selector string and clone that. - To refer back to the same element, keep it out of the cloned data. Store an
idordata-attribute and look the node up again withdocument.getElementByIdorquerySelector.
Finding the Offending Value
Error messages do not include a path, so a small diagnostic walker helps. It follows the parts of the structure that the algorithm walks. For any other object, it tries structuredClone on that object alone. A WeakSet keeps it from looping on circular references.
function findUncloneable(value, path = 'root', seen = new WeakSet()) {
const type = typeof value;
if (type === 'function' || type === 'symbol') return path;
if (value === null || type !== 'object') return null;
if (seen.has(value)) return null;
seen.add(value);
if (Array.isArray(value)) {
for (let i = 0; i < value.length; i++) {
const hit = findUncloneable(value[i], `${path}[${i}]`, seen);
if (hit) return hit;
}
return null;
}
if (value instanceof Map) {
let i = 0;
for (const [key, val] of value) {
const hit =
findUncloneable(key, `${path}<key ${i}>`, seen) ||
findUncloneable(val, `${path}<value ${i}>`, seen);
if (hit) return hit;
i++;
}
return null;
}
if (value instanceof Set) {
let i = 0;
for (const item of value) {
const hit = findUncloneable(item, `${path}<item ${i}>`, seen);
if (hit) return hit;
i++;
}
return null;
}
const proto = Object.getPrototypeOf(value);
if (proto === Object.prototype || proto === null) {
for (const key of Object.keys(value)) {
const hit = findUncloneable(value[key], `${path}.${key}`, seen);
if (hit) return hit;
}
return null;
}
try {
structuredClone(value);
return null;
} catch {
return path;
}
}
function cloneOrExplain(value) {
try {
return structuredClone(value);
} catch (err) {
if (err instanceof DOMException && err.name === 'DataCloneError') {
const where = findUncloneable(value) ?? 'an unknown location';
throw new TypeError(`Cannot clone: problem at ${where}`, { cause: err });
}
throw err;
}
}
const state = {
user: { name: 'Ada' },
settings: new Map([['theme', { dark: true, onChange: () => {} }]])
};
try {
cloneOrExplain(state);
} catch (err) {
console.log(err.message); // 'Cannot clone: problem at root.settings<value 0>.onChange'
console.log(err.cause.name); // 'DataCloneError'
}The walker reads getters, just as the algorithm does, and it cannot see through a Proxy that wraps a plain object. That is why cloneOrExplain falls back to "an unknown location" instead of assuming the walker always finds the problem. Use it while debugging or when reporting errors, not on every clone, because it repeats work.
Fixing the Data Instead of the Error
Catching DataCloneError tells you something is wrong. It does not give you a copy. These patterns stop the error from happening.
Keep behavior out of state
The most reliable fix is a design rule: data that will be cloned, posted to a worker or stored should contain only data. Put callbacks, element references and subscriptions in a separate object, or look them up by key.
const handlers = { save: () => console.log('saving') };
const formState = {
fields: { title: 'Draft' },
onSubmit: 'save' // a key into handlers, not the function itself
};
const copy = structuredClone(formState);
handlers[copy.onSubmit](); // 'saving'Strip unsupported values on purpose
When you don't control the input, build a cloneable version that leaves out the bad values on purpose. The walker below handles plain objects and arrays, which is the usual shape of configuration objects. Any other object is passed through unchanged, so structuredClone can copy it or reject it.
function withoutFunctions(value, seen = new WeakMap()) {
if (typeof value === 'function' || typeof value === 'symbol') return undefined;
if (value === null || typeof value !== 'object') return value;
if (seen.has(value)) return seen.get(value);
const proto = Object.getPrototypeOf(value);
if (Array.isArray(value)) {
const out = [];
seen.set(value, out);
for (const item of value) out.push(withoutFunctions(item, seen));
return out;
}
if (proto === Object.prototype || proto === null) {
const out = {};
seen.set(value, out);
for (const key of Object.keys(value)) {
const v = withoutFunctions(value[key], seen);
if (v !== undefined) out[key] = v;
}
return out;
}
return value;
}
const config = { retries: 3, log: console.log, nested: { when: new Date(0), cb() {} } };
const copy = structuredClone(withoutFunctions(config));
console.log(copy); // { retries: 3, nested: { when: 1970-01-01T00:00:00.000Z } }The seen map keeps shared and circular references intact in the intermediate structure, so structuredClone still receives the same graph shape. Functions inside arrays become undefined, which leaves the array the same length.
Copy class instances through their data
If an object fails only because it stores bound arrow functions, give the class toData() and fromData() methods. Clone the plain data and rebuild the instance from it. This also fixes the prototype loss covered in the next chapter.
Exercises
Exercise
Which of these calls throw a DataCloneError, and why? (a) structuredClone(new Error('x')) (b) structuredClone({ p: Promise.resolve(1) }) (c) structuredClone([1, Symbol.iterator]) (d) structuredClone(new (class { run() {} })())
Show answer
(b) and (c) throw. A Promise has internal state the algorithm cannot copy, and a symbol primitive is never cloneable, even inside an array. (a) works because Error objects are serializable. (d) works because run lives on the prototype, which the algorithm never visits. The result is the plain object {}.
Exercise
A teammate wraps every clone in try { return structuredClone(v); } catch { return JSON.parse(JSON.stringify(v)); }. Name two problems with this.
Show answer
First, it catches every exception, including errors thrown by getters, which hides real bugs. It should check err.name === 'DataCloneError' and rethrow anything else. Second, the fallback silently loses data. It drops the function that caused the failure, and it also turns Dates into strings, Maps and Sets into empty objects, and throws on circular references. The caller cannot tell which result it got.
Exercise
A getter on an object increments a counter, and a later property holds a function. After structuredClone throws, has the counter changed? What does this mean for clone calls on objects with side-effecting getters?
Show answer
Yes. The algorithm reads properties in order and runs each getter as it goes, so the getter ran before the function caused the throw. A clone that fails can still trigger side effects, so objects with side-effecting getters should be converted to plain data before you clone them.