Proxy Pattern
A proxy stands in for another object and controls access to it. JavaScript's Proxy type intercepts property reads, writes, and calls so you can log, validate, or virtualise the target.
Detailed Explanation
The design-pattern proxy is a stand-in: remote proxy (talk to a server), virtual proxy (lazy-create the real object), protection proxy (check permissions). The language feature new Proxy(target, handler) is how you implement those without writing a class that forwards every method by hand.
The handler can define traps: get, set, has, deleteProperty, apply, construct, ownKeys, and more. Missing traps fall through to the target. Reflect.get(...) is the correct default implementation so invariants stay intact.
const view = new Proxy(user, {
get(target, key, receiver) {
console.log("read", key);
return Reflect.get(target, key, receiver);
},
});
Use cases: reactive libraries (track which keys were read), API stubs, default values, revoked access (Proxy.revocable). A revocable proxy throws after revoke(); useful when you handed an object to untrusted code.
Proxies are not transparent. Map / Set / Date methods expect the real this. Wrapping a Map and forwarding get as a trap on the proxy object is not the same as map.get. Built-in methods look at internal slots, which the proxy does not have. Wrap the methods, or do not proxy those types.
What it costs you: speed and surprise. A get trap on a hot object is slower than a plain property. === still compares proxy and target as different objects. Proxy cannot hide private # fields of the target from the target's own methods, and it cannot invent private fields.
Reach for Proxy when many keys need the same policy. Reach for a facade when you want a smaller API, not interception. Reach for a decorator when you wrap one function.
Code Examples
const user = { email: "ada@example.com", role: "member" };
const logged = new Proxy(user, {
get(target, key, receiver) {
const value = Reflect.get(target, key, receiver);
if (key === "email") return value;
return value;
},
set(target, key, value, receiver) {
if (key === "role" && value !== "member" && value !== "admin") {
throw new TypeError("bad role");
}
return Reflect.set(target, key, value, receiver);
},
});
logged.role = "admin";
console.log(logged.role); // => adminconst { proxy, revoke } = Proxy.revocable(
{ secret: 1 },
{
get(t, k, r) {
return Reflect.get(t, k, r);
},
},
);
console.log(proxy.secret); // => 1
revoke();
try {
console.log(proxy.secret);
} catch (err) {
console.log(err.name); // => TypeError
}Common Gotchas
Built-ins with internal slots do not work as proxy targets for their methods
`new Proxy(new Map(), {})` + `.set` throws or misbehaves. Keep the real `Map` as `this`.
`proxy !== target`
identity-sensitive APIs (`WeakMap` keys, event targets) see two objects.
Always pair traps with `Reflect`
skipping invariants can throw `TypeError` on strict targets.