JavaScript Proxy Patterns and Pitfalls: Reactivity, Negative Indexes, Invariants and Limits
Put proxies to work and avoid their traps: change tracking and reactive state, negative array indexes, dynamic API clients and safe enums, why forwarding the receiver matters, the invariants that make traps throw, and why private fields, Map, Set and Date break through a proxy.
kvi5hnuCode Sprout team member7 min readOn this page
Article 105 covered the mechanics of proxies. This article covers what they're good for and where they go wrong. Real libraries rely on a handful of proven patterns, and each one comes with traps of its own. A few rules (the invariants) are enforced by the engine itself, and some objects simply can't be proxied transparently. Knowing those limits is what separates "I've read about Proxy" from "I can use it in production".
Pattern: change tracking (reactivity)
Frameworks like Vue 3 and MobX wrap state in proxies so they can find out when it changes and update the UI. Here's the core idea in a few lines:
function observe(obj, onChange, path = []) {
return new Proxy(obj, {
get(target, key, receiver) {
const value = Reflect.get(target, key, receiver);
return value !== null && typeof value === "object"
? observe(value, onChange, [...path, key]) // wrap nested objects lazily
: value;
},
set(target, key, value, receiver) {
const old = target[key];
const ok = Reflect.set(target, key, value, receiver);
if (ok && old !== value) onChange([...path, key].join("."), old, value);
return ok;
},
});
}
const state = observe({ user: { name: "Ana" }, cart: [] }, (path, from, to) =>
console.log(`${path}: ${JSON.stringify(from)} -> ${JSON.stringify(to)}`),
);
state.user.name = "Bo";
state.cart.push("tea");
state.user.name = "Bo"; // same value: no report
user.name: "Ana" -> "Bo"
cart.0: undefined -> "tea"
Notice that push worked without any special handling. push is an ordinary array method that sets index 0 and then length through the proxy, so the set trap saw both writes. The length write wasn't reported because setting index 0 had already changed length to 1.
Production versions add two refinements:
- Cache the wrappers in a
WeakMapfrom target to proxy. Otherwise every read ofstate.usercreates a new proxy, andstate.user !== state.user. - Batch notifications, for example scheduling one UI update per microtask instead of one per assignment.
Pattern: negative array indexes
function withNegativeIndexes(array) {
return new Proxy(array, {
get(target, key, receiver) {
if (typeof key === "string" && /^-\d+$/.test(key)) {
key = String(target.length + Number(key));
}
return Reflect.get(target, key, receiver);
},
});
}
const letters = withNegativeIndexes(["a", "b", "c"]);
console.log(letters[-1], letters[-3], letters[0], letters.length);
console.log(letters.map((x) => x.toUpperCase()), Array.isArray(letters));
c a a 3
[ 'A', 'B', 'C' ] true
Property keys arrive as strings ("-1"), so the trap matches them with a regex. Since ES2022, array.at(-1) covers the common case without a proxy; this pattern remains a good illustration of how traps work.
Pattern: dynamic methods and safe enums
A get trap can make up properties that don't exist anywhere, which is the trick behind fluent API clients and RPC stubs:
const api = new Proxy({}, {
get: (_, method) => (...segments) => `${String(method).toUpperCase()} /${segments.join("/")}`,
});
console.log(api.get("users", 7));
console.log(api.delete("posts", 3));
GET /users/7
DELETE /posts/3
And it can turn an object into an enum that fails loudly on typos:
function makeEnum(...names) {
const members = Object.freeze(Object.fromEntries(names.map((n) => [n, n])));
return new Proxy(members, {
get(target, key) {
if (typeof key === "string" && !(key in target)) throw new TypeError(`No enum member "${key}"`);
return target[key];
},
});
}
const Status = makeEnum("ACTIVE", "SUSPENDED");
console.log(Status.ACTIVE);
try {
Status.ACTVE;
} catch (err) {
console.log(err.message);
}
ACTIVE
No enum member "ACTVE"
Other well-known uses include:
- Mocks and spies in test frameworks;
- Immer, which records writes to a proxy "draft" and produces a new immutable object;
- ORMs that load related data lazily on first access;
- Membranes: wrapping an entire object graph so that untrusted code can be cut off all at once (sandboxes like SES use these).
Pitfall: forgetting the receiver
When a proxy is in an object's prototype chain (or wraps an object with getters), the getter must run with this set to the object the property was read from, the receiver. Writing target[key] instead of Reflect.get(target, key, receiver) loses it:
const base = {
_name: "base",
get name() {
return this._name;
},
};
const careless = new Proxy(base, { get: (target, key) => target[key] });
const correct = new Proxy(base, { get: (target, key, receiver) => Reflect.get(target, key, receiver) });
const child1 = Object.create(careless);
child1._name = "child";
const child2 = Object.create(correct);
child2._name = "child";
console.log(child1.name, child2.name);
base child
child1.name ran the getter with this === base, so it returned the wrong object's data. Always forward with Reflect and pass every argument through.
The invariants
A trap can't make an object lie in ways that contradict facts the language guarantees. After each trap runs, the engine checks its result against the target, and violations throw a TypeError:
| Trap | Invariant (for example) |
|---|---|
get | must return the actual value for a non-writable, non-configurable data property |
set | can't report success for changing a non-writable, non-configurable property |
has | can't hide a non-configurable property, or any property of a non-extensible target |
ownKeys | must list every non-configurable own key; for non-extensible targets, exactly the target's keys |
deleteProperty | can't report deleting a non-configurable property |
getPrototypeOf | must return the real prototype if the target is non-extensible |
const fixed = Object.defineProperty({}, "id", { value: 1, writable: false, configurable: false });
const attempts = {
"get lies": () => new Proxy(fixed, { get: () => 2 }).id,
"ownKeys hides": () => Object.keys(new Proxy(fixed, { ownKeys: () => [] })),
"has hides": () => "id" in new Proxy(fixed, { has: () => false }),
};
for (const [label, attempt] of Object.entries(attempts)) {
try {
attempt();
} catch (err) {
console.log(label, "->", err.name);
}
}
get lies -> TypeError
ownKeys hides -> TypeError
has hides -> TypeError
These invariants exist so that freezing an object really means something: code that checks Object.isFrozen(obj) can rely on it even when obj is a proxy. In practice they're only a problem when the target has frozen or non-configurable properties that the proxy tries to virtualize. The usual workaround is to proxy a separate, empty target and keep the real data elsewhere.
Limit: private fields and internal slots
Some objects keep their data inside the target in a place the proxy can't forward to: private class fields (#count), and the internal slots of built-ins like Map, Set, WeakMap, Date, Promise and DOM elements. Methods reached through the proxy run with this === proxy, look for that data on the proxy, and fail:

class Counter {
#count = 0;
increment() {
return ++this.#count;
}
}
const tests = {
"private field": () => new Proxy(new Counter(), {}).increment(),
"Map size": () => new Proxy(new Map([["a", 1]]), {}).size,
"Date method": () => new Proxy(new Date(0), {}).getTime(),
};
for (const [label, run] of Object.entries(tests)) {
try {
run();
} catch (err) {
console.log(label, "->", err.name);
}
}
private field -> TypeError
Map size -> TypeError
Date method -> TypeError
The common fix is a get trap that runs accessors and methods against the target:
function bindToTarget(obj) {
return new Proxy(obj, {
get(target, key) {
const value = Reflect.get(target, key, target); // getters see the target
return typeof value === "function" ? value.bind(target) : value;
},
});
}
const map = bindToTarget(new Map([["a", 1]]));
map.set("b", 2);
console.log(map.size, map.get("b"));
2 2
This makes calls work, but the proxy no longer sees what happens inside them. map.set changes the real map directly, so a change-tracking proxy wouldn't notice. That's why Vue and MobX ship special handlers that wrap each Map and Set method individually.
Limit: identity
A proxy is a different object from its target. proxy === target is false, so a Set or WeakMap holding the target doesn't recognize the proxy. Libraries also can't tell whether an object they received is the proxy or the original, which leads to "identity hazard" bugs when both leak into the same code. A good rule is to never let the raw target escape once you've wrapped it.
When not to use a Proxy
- Performance-critical code: every trapped operation costs a function call.
- Simple validation of known fields: a class with setters or a validation function is clearer and faster.
- Privacy: use
#privatefields or closures; proxies can be bypassed through the target. - Wrapping built-ins or classes with private fields: possible, but only with careful method binding.
Proxies are at their best when the set of properties is open-ended or unknown in advance, as in reactive state, dynamic APIs, mocks, sandboxes and dev-time checks.
Common questions
How does Vue's reactivity use proxies?
Vue 3 wraps state objects in a proxy whose get trap records which component read which property, and whose set trap schedules updates for the components that depend on it. It caches the proxies in a WeakMap and has special handlers for Map, Set and arrays.
What is a proxy invariant?
It's a rule the engine checks after a trap runs, so a proxy can't contradict fixed facts about its target, such as the value of a non-writable, non-configurable property or the keys of a non-extensible object. Violating one throws a TypeError.
Why does calling a method on a proxied Map throw?
Map methods operate on internal slots that exist only on real Map objects. Through a proxy, this is the proxy, which has no such slots. Bind the methods to the target in a get trap.
Can a Proxy intercept private field access?
No. #field access doesn't go through any trap, and it fails when this is a proxy. That's deliberate: private fields are truly private, even from proxies.
Summary
- Proxies shine for open-ended behavior: change tracking and reactivity, negative indexes, dynamic methods, safe enums, mocks and membranes.
- Always forward with
Reflectand pass the receiver, or getters run with the wrongthis. - Invariants stop traps from contradicting non-configurable properties and non-extensible targets; violations throw
TypeError. - Private fields and the internal slots of
Map,Set,Dateand similar built-ins don't work through a plain proxy; bind methods to the target. - A proxy is a distinct object, and every trap costs performance; use it where its flexibility pays off.
Review quiz
Check your understanding of property attributes, extensibility, prototypes, well-known symbols, Reflect and Proxy: Part 14 review quiz: Metaprogramming.
Practice Questions
Why does state.user === state.user print false with the observe function from this article, and how do you fix it?
Answer
The get trap creates a new proxy for the nested object on every read, so each access returns a different object. Cache the proxies in a WeakMap keyed by target:
const cache = new WeakMap();
function observe(obj, onChange) {
if (cache.has(obj)) return cache.get(obj);
const proxy = new Proxy(obj, { /* traps that call observe() for nested objects */ });
cache.set(obj, proxy);
return proxy;
}
What does this print, and why?
const target = Object.freeze({ id: 1 });
const p = new Proxy(target, { get: () => 99 });
console.log(p.id);
Answer
It throws a TypeError instead of printing. Freezing makes id non-writable and non-configurable, and the get invariant requires the trap to return the real value, 1.
Why does new Proxy(new Set([1]), {}).has(1) throw, and what's a fix?
Answer
Set.prototype.has needs the internal [[SetData]] slot, but it runs with this set to the proxy, which doesn't have it. Return methods bound to the target from a get trap:
const set = new Proxy(new Set([1]), {
get(target, key) {
const value = Reflect.get(target, key, target);
return typeof value === "function" ? value.bind(target) : value;
},
});
console.log(set.has(1)); // true
When is a Proxy the wrong tool for validating a User object with fixed fields like name and age?
Answer
When the fields are known in advance. A class with setters (or a validation function) is simpler, faster, works with private fields, and shows the rules explicitly. A proxy only pays off when the set of properties is open-ended.
Previous: JavaScript Proxy Explained: Handlers, Traps and Intercepting Object Operations
Next: JavaScript in the Browser: Scripts, Modules, defer, async and the Page Lifecycle

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.