⚡ Fix structuredClone Throwing on an Object That Worked Fine With JSON.stringify Because It Contains a Value structuredClone Explicitly Refuses to Clone
structuredClone and JSON.stringify/JSON.parse are often reached for interchangeably as a quick way to deep-copy an object, but they handle values neither can meaningfully represent in completely opposite ways: JSON.stringify silently drops a function property and converts an unsupported value into something nonsensical, all without ever throwing. structuredClone, built specifically as a real deep-clone algorithm rather than a text-serialization round-trip, explicitly throws a DataCloneError the moment it hits a value it can’t clone — a function, most DOM nodes, certain unsupported object types — so code switched from the old JSON-based copy trick to structuredClone for its better fidelity (real Dates, Maps, Sets, circular references) can start throwing on exactly the kind of object that used to ‘work’ simply because the old method never actually copied it correctly in the first place.
🔎 The Problem
const original = {
name: 'Widget',
onSave: () => console.log('saved'), // a function property
};
// Old approach - never threw, but silently dropped onSave entirely:
const copy1 = JSON.parse(JSON.stringify(original));
console.log(copy1); // { name: 'Widget' } - onSave is just gone, no error
// Switched to structuredClone for better fidelity:
const copy2 = structuredClone(original);
// Uncaught DOMException: Failed to execute 'structuredClone':
// function onSave could not be cloned.
✅ Fix: Strip Unclonable Values Deliberately Before Cloning
- Explicitly remove or extract function properties and other unclonable values before calling
structuredClone, rather than letting the clone call itself fail on data it was never going to meaningfully duplicate anyway. - If a function needs to travel alongside the cloned data, pass it separately rather than as a property of the object being cloned —
structuredClone‘s error is actually correct here, since a function genuinely can’t be deep-cloned the way a plain object can. - Treat the switch from a JSON-based copy to
structuredCloneas a chance to audit what’s actually in the object being copied, since the JSON approach’s silent data loss was very likely already a latent bug that simply never surfaced as an error.
🚨 Why This Is Dangerous
- Code that relied on the JSON round-trip’s silent dropping of a function property may have been shipping a copy that was already subtly wrong — missing a callback it should have preserved — for a long time before switching to a stricter cloning method finally made that gap visible as an actual error.
JSON.stringify’s silence about what it can’t represent isn’t a feature structuredClone copied — throwing loudly is the one case where the stricter tool is doing you a favor.
