Proxy & Reflect
Published by Brayan K
A Proxy wraps an object with handler traps that intercept operations like reading, writing, and checking properties, while Reflect provides matching methods to perform the default behavior — together they let you customize how objects respond to ordinary code.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
A trap observes an operation on the proxy, not every use of the target
A proxy has a separate identity from its target. Reads and writes through that proxy can be intercepted; code holding the original target can still use it directly. Start with one operation you need to customize, and forward the rest deliberately. A proxy is not a security sandbox around arbitrary code.
const target = { count: 2 };
// Keep a trace without changing the target data.
const reads = [];
const proxy = new Proxy(target, {
get(object, key, receiver) {
reads.push(String(key));
// Preserve getter receiver behavior while forwarding.
return Reflect.get(object, key, receiver);
}
});
console.log(proxy === target);
console.log(proxy.count, target.count);
console.log(reads.join(", "));
target.count = 5;
console.log(proxy.count);
// ✅ Expected output:
// false
// 2 2
// count
// 5Reflect.get performs the corresponding operation, with the supplied receiver for getters. It is not a magical way to bypass every proxy: passing the proxy itself back to Reflect.get inside its get trap would enter the trap again. Forward to the target parameter. Getters, Setters & Property Descriptors owns accessor receivers.
const changes = [];
const proxy = new Proxy({ nested: { count: 1 } }, {
set(target, key, value, receiver) {
changes.push(String(key));
return Reflect.set(target, key, value, receiver);
}
});
proxy.nested.count = 2;
console.log(changes.length, proxy.nested.count);
proxy.nested = { count: 3 };
console.log(changes.join(", "), proxy.nested.count);
// ✅ Expected output:
// 0 2
// nested 3The nested object is an ordinary reference returned by the outer read. Recursive observation needs explicit wrapping, identity caching and lifecycle choices. Advanced State Management owns application state design; this lesson does not suggest that one trap implements a complete reactive system.
Reflection reports success, while direct syntax applies its own failure rules
"use strict";
const target = { count: 1 };
const proxy = new Proxy(target, { set() { return false; } });
console.log(Reflect.set(proxy, "count", 2), target.count);
try { proxy.count = 3; }
catch (error) { console.log(error.name); }
console.log(target.count);
// ✅ Expected output:
// false 1
// TypeError
// 1"use strict";
const proxy = new Proxy({}, { set() { return false; } });
proxy.count = 3;
// ✅ Expected error:
// TypeError: 'set' on proxy: trap returned falsish for property 'count'A set trap must report a boolean-like success result. Returning true without storing anything claims success, so the value may remain unchanged. Prefer forwarding the actual Reflect.set result when ordinary storage is intended. Exceptions thrown by validation still propagate; reflection does not convert all failures into false.
const target = { count: 1 };
const proxy = new Proxy(target, {
set(object, key, value) {
if (typeof value !== "number") throw new TypeError("number required");
return Reflect.set(object, key, value);
}
});
Object.defineProperty(proxy, "count", { value: "bypassed" });
console.log(target.count);
// ✅ Expected output:
// bypassedObject.defineProperty invokes a different internal operation. If an API claims validation for both writes and definitions, it must handle both. Deletion, prototype changes and inherited receivers are also separate decisions. Hiding a property from one operation does not hide it from all reflection.
Preserve receiver behavior only when the target supports it
const seen = [];
const target = { count: 4, get double() { return this.count * 2; } };
const proxy = new Proxy(target, {
get(object, key, receiver) {
seen.push(String(key));
return Reflect.get(object, key, receiver);
}
});
console.log(proxy.double);
console.log(seen.join(", "));
// ✅ Expected output:
// 8
// double, countclass Counter {
#value = 3;
read() { return this.#value; }
}
const target = new Counter();
const proxy = new Proxy(target, {});
console.log(target.read());
try { console.log(proxy.read()); }
catch (error) { console.log(error.name); }
// ✅ Expected output:
// 3
// TypeErrorconst target = new Map([["a", 1]]);
const proxy = new Proxy(target, {});
try { console.log(proxy.size); }
catch (error) { console.log(error.name); }
console.log(Reflect.get(target, "size", target));
// ✅ Expected output:
// TypeError
// 1Private fields and built-in internal slots belong to the target, not automatically to the proxy. Binding methods or changing receivers can make a particular wrapper work, but also changes identity and receiver semantics. A blanket “bind every function” trap is not a transparent universal solution. Prototype Chain & Advanced OOP Patterns owns class/prototype mechanics.
Invariants constrain what a handler is allowed to claim
const target = {};
Object.defineProperty(target, "code", { value: 7, writable: false, configurable: false });
const proxy = new Proxy(target, { get() { return 8; } });
try { console.log(proxy.code); }
catch (error) { console.log(error.name); }
console.log(target.code);
// ✅ Expected output:
// TypeError
// 7const locked = Object.seal({ code: 7 });
for (const handler of [
{ ownKeys() { return []; } },
{ ownKeys() { return ["code", "code"]; } }
]) {
try { Reflect.ownKeys(new Proxy(locked, handler)); }
catch (error) { console.log(error.name); }
}
// ✅ Expected output:
// TypeError
// TypeErrorThese are language invariants, not optional best practices. For a non-extensible target, ownKeys must report exactly its own keys; duplicates are never allowed. A get trap must preserve the value of a non-writable, non-configurable own data property. The runtime throws when these restrictions are violated, even if the trap itself returns normally.
const target = { count: 2 };
const { proxy, revoke } = Proxy.revocable(target, {});
console.log(proxy.count);
revoke();
revoke();
try { console.log(proxy.count); }
catch (error) { console.log(error.name); }
console.log(target.count);
// ✅ Expected output:
// 2
// TypeError
// 2Revocation is useful for ending access through a particular handle. It does not erase data, revoke copies of nested values already obtained, or invalidate the original target. JavaScript Memory Management & Garbage Collection owns reference lifetime; Client-Side Security Essentials (XSS, CSRF, Sanitisation) owns actual authorization boundaries.
Guided exercise: forward a validated write
Fill the literal hints. Validate the count before forwarding, and return the real write result. This small exercise accepts direct writes only; the brief handles definition and receiver boundaries too.
const target = { count: 1 };
const proxy = new Proxy(target, {
set(object, key, value) {
if (key !== "count" || !Number.___(value)) return false; // 👉 replace ___ with isInteger
return Reflect.___(object, key, value); // 👉 replace ___ with set
}
});
console.log(Reflect.set(proxy, "count", ___)); // 👉 replace ___ with 4
console.log(target.count, Reflect.set(proxy, "extra", 9));
// ✅ Expected output:
// true
// 4 falseBrief: a narrowly defined settings handle
Implement createSettings with a sealed null-prototype target containing theme "light" and limit 20. Expose settings, a proxy, and snapshot(), which returns a fresh frozen ordinary record. The raw target stays in the closure. Valid themes are light and dark; valid limits are integers 1–100. Invalid values for known keys throw TypeError("invalid theme") or TypeError("invalid limit") before mutation.
Unknown keys return false from write/definition traps. Direct set operations must use this proxy as receiver; reject alternate receivers. Allow defineProperty only when its normalized descriptor contains exactly a value field for a known key. Reject deletion, prototype changes and attempts to redefine flags or accessors. These deliberate limits mean Object.freeze(settings) is refused; the returned outer API handle itself is frozen.
Use the target as the receiver when forwarding an approved set so it does not re-enter the proxy’s defineProperty trap. The target contains only the two data properties, making that choice explicit and narrow. This is an educational validation API, not a general membrane or security barrier.
function createSettings() {
const target = Object.seal(Object.assign(Object.create(null), { theme: "light", limit: 20 }));
function validate(key, value) {
if (key === "theme") {
if (value !== "light" && value !== "dark") throw new TypeError("invalid theme");
} else if (key === "limit") {
if (!Number.isInteger(value) || value < 1 || value > 100) throw new TypeError("invalid limit");
} else return false;
return true;
}
let settings;
settings = new Proxy(target, {
set(object, key, value, receiver) {
if (receiver !== settings) return false;
if (!validate(key, value)) return false;
return Reflect.set(object, key, value, object);
},
defineProperty(object, key, descriptor) {
if (!Object.hasOwn(descriptor, "value") ||
Reflect.ownKeys(descriptor).some(name => name !== "value")) return false;
if (!validate(key, descriptor.value)) return false;
return Reflect.defineProperty(object, key, descriptor);
},
deleteProperty() { return false; },
setPrototypeOf() { return false; }
});
return Object.freeze({
settings,
snapshot() { return Object.freeze({ theme: target.theme, limit: target.limit }); }
});
}
const api = createSettings();
api.settings.theme = "dark";
console.log(Reflect.defineProperty(api.settings, "limit", { value: 5 }));
console.log(JSON.stringify(api.snapshot()));
console.log(Reflect.set(api.settings, "extra", 1));
console.log(Reflect.deleteProperty(api.settings, "theme"));
console.log(Reflect.defineProperty(api.settings, "limit", { value: 6, writable: false }));
console.log(Reflect.set(api.settings, "limit", 7, {}));
try { api.settings.limit = 0; } catch (error) { console.log(error.name, error.message); }
console.log(JSON.stringify(api.snapshot()), Object.isFrozen(api));
// ✅ Expected output:
// true
// {"theme":"dark","limit":5}
// false
// false
// false
// false
// TypeError invalid limit
// {"theme":"dark","limit":5} true
Practice quiz
What does this complete program print? const target = {}; const proxy = new Proxy(target, {}); console.log(proxy === target);
- false
- true
- undefined
- TypeError
Answer: false. The proxy has distinct identity.
What does this complete program print? let n = 0; const target = { a: 1 }; const proxy = new Proxy(target, { get(t, k) { n++; return t[k]; } }); console.log(target.a, n);
- 1 1
- 1 0
- undefined 1
- undefined 0
Answer: 1 0. Direct target access bypasses the proxy.
What does this complete program print? const target = { a: 1 }; const proxy = new Proxy(target, { set() { return false; } }); console.log(Reflect.set(proxy, "a", 2), target.a);
- true 2
- false 2
- false 1
- true 1
Answer: false 1. The refused write reports false and does not mutate the target.
What does this complete program print? const target = { a: 1 }; const proxy = new Proxy(target, { set() { return true; } }); proxy.a = 2; console.log(target.a);
- 2
- undefined
- TypeError
- 1
Answer: 1. A trap claiming success need not perform storage unless its implementation does so.
What does this complete program print? let n = 0; const proxy = new Proxy({ inner: { a: 1 } }, { set(t,k,v) { n++; return Reflect.set(t,k,v); } }); proxy.inner.a = 2; console.log(n);
- 0
- 1
- 2
- TypeError
Answer: 0. The nested object is not automatically wrapped.
What does this complete program print? const base = { get x() { return this.n; } }; console.log(Reflect.get(base, "x", { n: 8 }));
- undefined
- 8
- 0
- TypeError
Answer: 8. The third argument supplies the accessor receiver.
What does this complete program print? const target = Object.freeze({ x: 1 }); const proxy = new Proxy(target, { get() { return 2; } }); try { console.log(proxy.x); } catch (e) { console.log(e.name); }
- 1
- 2
- TypeError
- undefined
Answer: TypeError. The get invariant forbids changing this locked data-property value.
What does this complete program print? const target = { x: 1 }; const { proxy, revoke } = Proxy.revocable(target, {}); revoke(); console.log(target.x);
- undefined
- TypeError
- null
- 1
Answer: 1. Revocation affects the proxy handle, not the raw target.
Continue this course
- Previous: Getters, Setters & Property Descriptors
- Next: BigInt & Number Precision — Work with integers beyond MAX_SAFE_INTEGER and avoid precision loss
- Quick reference: JavaScript cheat sheet