javascript 35 lines · 7 steps

Deep cloning with structuredClone

How to build safe deep copies with structuredClone, including capability checks and cloner-aware error handling.

Explained by highlit
1export function cloneState(state) {
2 if (typeof structuredClone !== "function") {
3 throw new Error("structuredClone is not available in this runtime");
4 }
5 
6 try {
7 return structuredClone(state);
8 } catch (err) {
9 if (err instanceof DOMException && err.name === "DataCloneError") {
10 throw new TypeError(
11 "State contains non-cloneable values (functions, DOM nodes, or class instances with private fields)",
12 { cause: err }
13 );
14 }
15 throw err;
16 }
17}
18 
19export function withTransferables(payload, transfer) {
20 return structuredClone(payload, { transfer });
21}
22 
23export function snapshotStore(store) {
24 const draft = {
25 entities: store.entities,
26 filters: new Map(store.filters),
27 lastFetched: new Date(store.lastFetched),
28 pending: new Set(store.pending),
29 buffer: store.buffer,
30 };
31 
32 const clone = structuredClone(draft);
33 Object.freeze(clone);
34 return clone;
35}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1structuredClone deep-copies Maps, Sets, Dates, and typed arrays that JSON round-tripping would silently destroy.
  2. 2Cloning throws a DataCloneError DOMException for functions, DOM nodes, and other non-serializable values, so guard for it.
  3. 3Pairing a clone with Object.freeze yields an isolated, tamper-proof snapshot of mutable state.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Deep cloning with structuredClone — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code