DOMException: Could not be cloned — DataCloneError from structuredClone()
structuredClone() can't clone functions, class instances with non-plain internals, or objects holding open handles — it only supports the structured clone algorithm's data types. Strip the object down to plain, clonable data first, or write a manual serialization step for the parts that don't qualify.
What causes this error
structuredClone() is a global built into Node.js that deep-clones data using the same algorithm browsers use for `postMessage`. It supports plain objects, arrays, Maps, Sets, Dates, and typed arrays — but not functions, DOM-like objects, class instances with private fields tied to native resources, or anything holding an open file/socket handle.
The Fix
// Wrong — class instance wraps a live database connection
class UserSession {
constructor(dbConnection) { this.dbConnection = dbConnection; }
}
structuredClone(new UserSession(conn)); // DataCloneError
// Fix — clone only the plain data you actually need
const plain = { id: session.id, userId: session.userId, createdAt: session.createdAt };
const copy = structuredClone(plain);Common causes / variations
- Cloning an ORM model instance instead of a plain object built from its fields
- Cloning an object that (directly or nested) contains a function, Promise, or WeakMap
- Passing a class instance across a `worker_threads` boundary without first converting it to plain data
Related errors
See also: postMessage DataCloneError in worker_threads, Only plain objects can be passed to Client Components.
Comments
Loading comments...