Sub topic 7
Functions, DOM Nodes and DataCloneError
This chapter assumes you know JavaScript objects and arrays, object spread and try/catch, and that you have already used structuredClone on plain data, Dates, Maps and Sets. Here you will see which values structuredClone refuses to copy and how to handle that refusal in your code.
The working model: clone data, not behavior
The structured clone algorithm copies data, meaning values that can be fully described by their contents. A function also carries behavior and a closure over variables in its scope. Neither of these can be rebuilt in another context, such as a worker thread. The algorithm does not guess what to do with such a value. When it meets one, it stops and throws a DOMException whose name is 'DataCloneError'.
try {
structuredClone({ onClick: () => {} });
} catch (err) {
console.log(err.name); // 'DataCloneError'
}A JSON round-trip behaves differently. JSON.stringify silently drops function-valued properties, so a bug can go unnoticed. structuredClone fails loudly, so you find the problem at the moment you try to copy.
How the error happens
The algorithm walks the whole value graph. One bad value anywhere in it, at any depth, makes the whole call throw. You never get a partial copy back.
const config = {
theme: 'dark',
panels: [{ id: 1, render() { return '<div>'; } }]
};
try {
structuredClone(config);
} catch (err) {
console.log(err.name); // 'DataCloneError'
}The method shorthand render() {} creates a function, so the nested panel is enough to make the call fail.
Values that cause DataCloneError
| Value | Why it fails | What to do instead |
|---|---|---|
| Functions, arrow functions, methods, classes | Code and closures cannot be serialized | Separate them from the data and reattach them after cloning |
| DOM nodes such as `document.body` (browsers) | They belong to a live document | Use `node.cloneNode(true)` |
| Symbol values such as `Symbol('id')` | Symbols are unique to their realm | Store a string identifier |
| `WeakMap`, `WeakSet`, `WeakRef` | Their contents cannot be listed | Use `Map` or `Set` if you need to copy them |
| `Promise` | It represents a pending computation | Await it and clone the resolved value |
DOM nodes exist only in browsers. Run this example in a browser console:
try {
structuredClone(document.body);
} catch (err) {
console.log(err.name); // 'DataCloneError'
}
const copyOfBody = document.body.cloneNode(true); // works: a detached DOM copy
console.log(copyOfBody.tagName); // 'BODY'Handling the error
Check err.name and do not match on err.message. The message text differs between browsers and Node.js. Rethrow anything that is not a clone error so that unrelated bugs still surface.
function tryClone(value) {
try {
return { ok: true, value: structuredClone(value) };
} catch (err) {
if (err instanceof DOMException && err.name === 'DataCloneError') {
return { ok: false, error: err };
}
throw err;
}
}
console.log(tryClone({ a: 1 }).ok); // true
console.log(tryClone({ fn() {} }).ok); // false
console.log(tryClone(Symbol('x')).ok); // falseDOMException is a global in browsers and in Node.js 17 and later.
Separating behavior from data
Catching the error is a fallback. A better fix is to clone only the data. Pull the functions out with destructuring, clone the rest, then attach the functions to the copy.
const widget = {
state: { count: 1, tags: new Set(['new']) },
onClick() { return 'clicked'; }
};
const { onClick, ...data } = widget;
const copy = { ...structuredClone(data), onClick };
copy.state.tags.add('edited');
console.log(widget.state.tags.has('edited')); // false
console.log(copy.onClick()); // 'clicked'The copy shares the function with the original, which is usually what you want because functions are not mutated. Everything else in the copy is independent of the original.
Common mistakes
- Assuming that methods on an object literal are skipped. They are functions, so they throw.
- Cloning state that holds a pending
Promisefrom a fetch. Await it first. - Putting DOM element references into a state object, then cloning that state.
- Testing
err.message.includes('could not be cloned'), which breaks on other runtimes.
Exercise
What does this code log, and why? const r = tryClone({ list: [1, 2, { id: Symbol('a') }] }); console.log(r.ok); (tryClone is the helper from this chapter.)
Show answer
It logs false. The Symbol is stored as a property value at depth three, and the structured clone algorithm throws DataCloneError on any Symbol value no matter how deeply it is nested. tryClone catches that error and returns ok: false.
Exercise
You need a deep copy of { user: { name: 'Ada' }, save: () => {} } that keeps a working save function. Write it without try/catch.
Show answer
const { save, ...rest } = obj; const copy = { ...structuredClone(rest), save }; This clones only the data, then reattaches the original function to the copy.