Proxy and Reflect
A Proxy lets you intercept the fundamental operations on an object, which is how reactivity, validation and observable state are built.
A wraps a target and a handler of traps. Each trap intercepts one operation: get, set, has, deleteProperty and more. Reflect provides the default behaviour for each, so a trap can add something and then carry on normally.
EXERCISE
1Intercepting the Fundamentals
Every property read and write on an object goes through operations you can now take over.
Until now, reading obj.name has been something the engine does and you observe. A Proxy lets you sit in the middle of it.
The shape:
const target = { name: "Ada", age: 36 };
const proxy = new Proxy(target, {
get(obj, key) {
console.log(`reading ${String(key)}`);
return obj[key];
},
});
console.log(proxy.name);
// reading name
// Ada
Two arguments: the object being wrapped, and a handler holding traps. Any operation with no trap passes straight through to the target untouched.
That is a genuinely different kind of power from anything else in the course. A getter intercepts one named property you decided about in advance. A Proxy intercepts the operation itself, so it applies to every key, including ones that do not exist yet and ones nobody thought of when the object was written.
The traps you will actually use:
new Proxy(target, {
get(obj, key, receiver) { }, // obj.key
set(obj, key, value, receiver) { }, // obj.key = value
has(obj, key) { }, // "key" in obj
deleteProperty(obj, key) { }, // delete obj.key
ownKeys(obj) { }, // Object.keys, for-in, spread
apply(fn, thisArg, args) { }, // fn(...)
construct(fn, args) { }, // new fn(...)
});
There are thirteen in total. These seven cover essentially everything you will meet.
Validation, which is the clearest first use:
const user = new Proxy({}, {
set(obj, key, value) {
if (key === "age" && (!Number.isInteger(value) || value < 0)) {
throw new TypeError("age must be a non-negative integer");
}
obj[key] = value;
return true;
},
});
user.age = 36; // fine
// user.age = -5; // TypeError: age must be a non-negative integer
A set trap must return true to report success. Returning a falsy value throws in strict mode, which every module is, and forgetting the return is the most common Proxy bug there is.
A default value for missing keys:
function withDefault(obj, fallback) {
return new Proxy(obj, {
get(target, key) {
return key in target ? target[key] : fallback;
},
});
}
const counts = withDefault({}, 0);
counts.apples += 1;
console.log(counts.apples); // 1
console.log(counts.pears); // 0, not undefined
And a negative array index, which JavaScript has never had:
function negativeIndex(array) {
return new Proxy(array, {
get(target, key) {
const index = Number(key);
if (Number.isInteger(index) && index < 0) {
return target[target.length + index];
}
return target[key];
},
});
}
const items = negativeIndex(["a", "b", "c"]);
console.log(items[-1]); // c
console.log(items[0]); // a
Note the key arrives as a string, always. Number(key) is doing real work there, and forgetting it is why a first attempt at this usually fails.
EXERCISE
2Reflect, and How Reactivity Works
Reflect gives every trap its default behaviour as a function, which is what makes writing a correct trap practical.
Writing obj[key] inside a get trap works for simple cases and is subtly wrong. Reflect provides the operation the engine would have performed.
The pairing:
// Every trap has a matching Reflect method with the same arguments.
Reflect.get(obj, key, receiver);
Reflect.set(obj, key, value, receiver);
Reflect.has(obj, key);
Reflect.deleteProperty(obj, key);
Reflect.ownKeys(obj);
Which makes the common trap a one-liner:
const proxy = new Proxy(target, {
get(obj, key, receiver) {
track(key);
return Reflect.get(obj, key, receiver);
},
set(obj, key, value, receiver) {
const result = Reflect.set(obj, key, value, receiver);
notify(key);
return result;
},
});
Reflect.set returns the boolean the trap is required to return, so you no longer have to remember return true.
Why the receiver argument matters:
const target = {
_value: 1,
get value() {
return this._value;
},
};
const proxy = new Proxy(target, {
get(obj, key, receiver) {
return obj[key]; // WRONG: `this` becomes target
// return Reflect.get(obj, key, receiver); // correct
},
});
With obj[key], a getter on the target runs with this pointing at the target, so it bypasses the proxy and nested reads are never tracked. Reflect.get with the receiver keeps this as the proxy. For a reactivity system that difference decides whether nested properties are observed at all.
And that is essentially how Vue 3 works:
function reactive(obj) {
return new Proxy(obj, {
get(target, key, receiver) {
trackDependency(target, key);
const value = Reflect.get(target, key, receiver);
return typeof value === "object" && value !== null
? reactive(value) // wrap nested objects lazily
: value;
},
set(target, key, value, receiver) {
const result = Reflect.set(target, key, value, receiver);
triggerEffects(target, key);
return result;
},
});
}
const state = reactive({ count: 0, user: { name: "Ada" } });
state.count += 1; // triggers whatever depended on count
state.user.name = "Grace"; // nested, and still tracked
Reading records which effect depended on which key; writing re-runs those effects. Nested objects are wrapped on access rather than up front, so a large object costs nothing until you touch it.
This is why Vue 3 could drop the limitations of Vue 2, which used Object.defineProperty and could not detect a new property or an array index assignment. A Proxy intercepts the operation itself, so both work.
What it cannot do:
class Account {
#balance = 0;
getBalance() {
return this.#balance;
}
}
const proxied = new Proxy(new Account(), {});
// proxied.getBalance();
// TypeError: Cannot read private member #balance from an object
// whose class did not declare it
Private fields from Unit 3 are keyed to the actual instance, and the proxy is a different object. There is no trap for a private field, by design, which is the strongest evidence that # privacy is real.
Pro Tip: Always use
Reflectinside a trap rather than reimplementing the operation. It gives you the correct default including the receiver, it returns the right value for traps that require one, and it means a trap that adds logging stays a two-line change rather than a reimplementation you have to keep correct.
EXERCISE
3When Not to Reach for a Proxy
The feature is powerful enough that the useful question is when to leave it alone.
A Proxy can intercept anything, which makes it tempting for problems that have simpler answers.
When a getter or setter is enough:
// Over-engineered
const user = new Proxy({}, {
set(obj, key, value) {
if (key === "email" && !value.includes("@")) {
throw new TypeError("invalid email");
}
obj[key] = value;
return true;
},
});
// A class with a setter, from Unit 3
class User {
#email;
set email(value) {
if (!value.includes("@")) throw new TypeError("invalid email");
this.#email = value;
}
get email() {
return this.#email;
}
}
The class version is obvious at the point of definition. Someone reading it sees where validation lives; with a Proxy they have to find where the object was wrapped, which may be a different file entirely.
The general rule: a Proxy is invisible at the use site.
const settings = getSettings();
settings.theme = "dark"; // is this plain? proxied? validated? logged?
Nothing in that code says. That invisibility is exactly what makes reactivity work and exactly what makes harder, so it should be a deliberate trade rather than a default.
Where it genuinely earns its place:
// 1. Reactivity, where the whole point is that the user's code
// looks like ordinary property access.
// 2. A mock or spy in a test, recording calls on a real object.
// 3. An API client where any property becomes a request path:
const api = new Proxy({}, {
get(_, resource) {
return (id) => fetch(`/api/${String(resource)}/${id}`);
},
});
await api.users(1);
await api.posts(7);
All three share a property: the alternative would be worse for the person using it. A reactivity system without a Proxy means calling .value everywhere; an client without one means writing a method per resource.
The pattern across those three is worth naming. A Proxy pays for itself when the alternative makes life worse for the person using your code, not when it makes life easier for the person writing it. That is a high bar, and most uses of a Proxy do not clear it.
Two practical warnings:
// Proxies do not compose well. Wrapping a proxy in another proxy
// works and becomes very hard to reason about.
// Traps must obey invariants. A get trap that returns a different
// value each time for a non-configurable, non-writable property
// throws a TypeError, because the engine enforces consistency.
const target = Object.freeze({ a: 1 });
const p = new Proxy(target, {
get() {
return Math.random();
},
});
// p.a; TypeError: 'get' on proxy: property 'a' is a read-only
// and non-configurable data property
And one thing worth knowing exists:
const { proxy, revoke } = Proxy.revocable(target, handler);
proxy.name; // works
revoke();
// proxy.name; TypeError: Cannot perform 'get' on a revoked proxy
revocable lets you hand out access and take it back, which is the one capability nothing else in the language offers.
