⚡ JavaScript: Fix a WeakMap Losing Entries After a Structured Clone
A WeakMap only ever matches a key by strict object reference, which is exactly what makes it silently break the moment an object crosses a structuredClone() boundary — passing data to a Web Worker through postMessage(), or cloning it directly — because structured cloning produces a brand-new object graph with nested objects that look identical to the originals but are different references entirely. A cache keyed on the pre-clone object finds nothing for the post-clone one, even though every property on it compares equal.
🔎 The Problem
const metadataCache = new WeakMap();
const node = { id: 42, payload: {} };
metadataCache.set(node.payload, { lastAccessed: Date.now() });
worker.postMessage(node); // internally structured-clones `node`
// inside the worker, `node.payload` is a NEW object reference -
// metadataCache.get(clonedNode.payload) returns undefined, even
// though clonedNode.payload deep-equals the original payload
✅ Fix: Key the Cache by a Stable ID, Not by Reference, Across a Clone Boundary
- Never key a
WeakMapon an object you expect to survive astructuredClone(), apostMessage(), or an IndexedDB round-trip — reference identity is exactly what a structured clone does not preserve. - Use a stable string or numeric id carried as a plain property on the object instead, and key a regular
Map(or re-derive the association) on that id after the clone, since ids survive cloning perfectly while references never do. - If the association genuinely must live on the object itself across the boundary, send it explicitly as part of the cloned payload rather than relying on a side-table the clone has no way of knowing about.
🚨 Why This Is Dangerous
- Debugging a ‘random’ cache-miss bug for hours because every object involved deep-equals its counterpart in logs on both sides of a postMessage boundary, when the actual cause — a WeakMap doing a reference comparison, not a value comparison — never shows up in a console.log at all.
Deep-equal and the-same-reference are different questions, and WeakMap only ever answers the second one.

