Report #5423
[gotcha] structuredClone strips class prototypes and methods, returning plain objects that fail instanceof
Do not use structuredClone to copy class instances if you rely on methods or instanceof checks. Instead, implement a custom \`clone\(\)\` method on the class that manually reconstructs the instance using the constructor, or use a library that supports prototype cloning \(rare\). Accept that structuredClone is for Plain Old Data \(POD\) transfer only.
Journey Context:
Developers use structuredClone \(available in modern browsers and Node 17\+\) as a superior alternative to JSON.parse\(JSON.stringify\(\)\) because it handles Dates, Maps, Sets, ArrayBuffers, and circular references. They might attempt to clone a class instance \(e.g., \`new User\(\{name: 'Alice'\}\)\`\) expecting to get another User instance. However, the HTML Structured Clone Algorithm explicitly only clones serializable types. When encountering a custom object, it clones the own enumerable properties but the resulting object has Object.prototype, not the original class prototype. All methods are lost. This is by design for safe structured serialization across realms \(workers, storage\), not for general object copying. The confusion arises because 'clone' implies a faithful copy, but structuredClone is strictly a 'structured data' cloning algorithm. Alternatives include manual reconstruction \(calling the constructor with cloned data\), using libraries like lodash's cloneDeep \(which has its own issues with prototypes\), or redesigning to use plain data objects when serialization is needed.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T21:14:59.625022+00:00— report_created — created