⚡ Fix a Proxy-Wrapped Object Losing Its Custom Methods After It’s Passed Through JSON.stringify and Rebuilt With JSON.parse
JSON.stringify only serializes an object’s own enumerable data properties – it has no concept of a Proxy’s traps, a class’s prototype methods, or any function-valued property, all of which are silently skipped. Round-tripping a reactive object through JSON.stringify and JSON.parse for storage or messaging produces a plain object with the right data but none of the original object’s behavior, and nothing in that process warns that anything was lost.
🔎 The Problem
const state = makeReactive({ count: 0, increment() {
this.count++;
} }); // makeReactive wraps the object in a Proxy
state.increment(); // works: count === 1, and the
// Proxy's set trap fires reactively
const json = JSON.stringify(state);
// '{"count":1}' - the increment method is simply absent;
// JSON.stringify never serializes function-valued properties
const restored = JSON.parse(json);
restored.increment();
// TypeError: restored.increment is not a function
restored.count++; // works, but this is now a PLAIN
// object - no Proxy, no reactivity,
// nothing observes this change
✅ Fix: Separate the Data You Serialize From the Behavior You Attach
- Serialize only the plain data shape (count, in this example) and re-wrap it with makeReactive again after JSON.parse, instead of expecting the round trip to preserve the Proxy or any methods.
- If the object’s class defines the methods instead of each instance, use a custom toJSON or a reviver function so you can reconstruct a real instance of that class after parsing, rather than a bare object literal.
- For passing reactive state across a worker or network boundary specifically, prefer structuredClone where it’s supported for plain data, and still re-apply reactivity on the receiving side – structuredClone doesn’t preserve Proxy behavior either.
🚨 Why This Is Dangerous
- This failure is silent by default – JSON.stringify drops function properties without any warning or error, so the bug only surfaces later as ‘increment is not a function,’ far from the actual serialization call that caused it.
JSON.stringify doesn’t serialize your object – it serializes the parts of it that happen to look like JSON already.
