Difficulty: Advanced
What are the Proxy and Reflect APIs in JavaScript, and how do they let you intercept and customise fundamental object operations (meta-programming)?
A Proxy wraps a target object and lets you intercept fundamental operations on it, such as reading a property, assigning one, deleting one, checking in, or calling a function, through handler methods called traps. Reflect is a built-in namespace object whose static methods (Reflect.get, Reflect.set, Reflect.has and so on) perform the default version of each of those operations, so a trap can add behaviour and then forward to the normal semantics. Together they give JavaScript real meta-programming: code that changes how objects behave rather than what data they hold.
new Proxy(target, handler) returns a new object. Every operation on the proxy is routed to the matching trap on handler; if the trap is missing, the operation falls through to the target unchanged. There are 13 traps, one for each internal method in the spec:
get, set, has, deleteProperty, ownKeysgetOwnPropertyDescriptor, definePropertygetPrototypeOf, setPrototypeOf, isExtensible, preventExtensionsapply and construct (only meaningful when the target is a function)A trap receives the target, the property key and, for get and set, a receiver argument, which is the object the operation was originally performed on (usually the proxy itself, or an object that inherits from it).
Before ES2015, the default behaviours were scattered: delete obj[k], k in obj, Object.defineProperty, Function.prototype.apply. Reflect gathers them into one place, with one method per trap and identical signatures. That makes forwarding trivial: return Reflect.set(target, key, value, receiver).
Passing receiver matters. If the target has a getter that uses this, target[key] runs the getter with this set to the raw target, bypassing the proxy. Reflect.get(target, key, receiver) runs it with this set to the proxy, so nested accesses are still intercepted. Reflect methods also return booleans (Reflect.set, Reflect.defineProperty) instead of throwing, which is exactly what set and defineProperty traps must return.
reactive() uses a get trap to track which component read a property and a set trap to trigger re-renders. MobX and Immer also rely on proxies (Immer records writes to a draft and produces an immutable copy).order.amountInPaise = -100 at the moment of assignment.undefined.get trap can turn api.users.list() into an HTTP call without defining every method.| Aspect | Proxy | Object.defineProperty |
|---|---|---|
| Scope | Whole object, including keys added later | One existing property at a time |
| Detects new / deleted keys | Yes (set, deleteProperty) | No |
Array index and length changes | Yes | Not reliably |
| Identity | Proxy is a different object from target | Same object |
| Polyfillable | No | Yes (ES5) |
This table is why Vue 2 needed Vue.set for new keys and Vue 3 does not.
get trap must return its real value or a TypeError is thrown.Map, Set, Date and private class fields store data in internal slots. new Proxy(new Map(), {}).get('x') throws because this is the proxy, not the Map. You must bind methods to the target.proxy === target is false, so WeakMap lookups or Set membership keyed on the original object will miss.Proxy.revocable() returns { proxy, revoke }; after revoke(), any operation throws. Useful for handing temporary access to untrusted code.const orderValidator = {
set(target, key, value, receiver) {
if (key === 'amountInPaise') {
if (!Number.isInteger(value)) throw new TypeError('amountInPaise must be an integer');
if (value <= 0) throw new RangeError('amountInPaise must be positive');
}
// Forward to default behaviour; returns true on success
return Reflect.set(target, key, value, receiver);
},
deleteProperty(target, key) {
if (key === 'id') throw new Error('id cannot be deleted');
return Reflect.deleteProperty(target, key);
},
};
const order = new Proxy({ id: 'ord_1' }, orderValidator);
order.amountInPaise = 49900;
console.log(order.amountInPaise);
try {
order.amountInPaise = -5;
} catch (e) {
console.log(e.name + ': ' + e.message);
}
The set trap validates before writing, and Reflect.set does the real assignment while preserving the receiver. Returning its boolean result keeps strict-mode semantics correct.
let activeEffect = null;
const deps = new Map(); // key -> Set of effects
function reactive(obj) {
return new Proxy(obj, {
get(target, key, receiver) {
if (activeEffect) {
if (!deps.has(key)) deps.set(key, new Set());
deps.get(key).add(activeEffect); // track
}
return Reflect.get(target, key, receiver);
},
set(target, key, value, receiver) {
const ok = Reflect.set(target, key, value, receiver);
deps.get(key)?.forEach(fn => fn()); // trigger
return ok;
},
});
}
function effect(fn) {
activeEffect = fn;
fn();
activeEffect = null;
}
const cart = reactive({ items: 2 });
effect(() => console.log('Cart badge:', cart.items));
cart.items = 3;
Reading a property inside an effect records a dependency, and writing to it re-runs every dependent effect. Real libraries add per-object dependency maps, batching and deep wrapping, but the core mechanism is these two traps.
const map = new Map([['a', 1]]);
const broken = new Proxy(map, {});
try {
broken.get('a');
} catch (e) {
console.log(e.constructor.name);
}
const fixed = new Proxy(map, {
get(target, key, receiver) {
const value = Reflect.get(target, key, receiver);
// Bind methods so `this` is the real Map, not the proxy
return typeof value === 'function' ? value.bind(target) : value;
},
});
console.log(fixed.get('a'));
Map methods read an internal slot that only exists on the real Map, so they fail when called with the proxy as this. Binding methods to the target fixes it, which is why reactive libraries special-case collections.
Proxy, Reflect, Handler Traps, Invariants, Meta-programming, Reactivity