Proxy & Reflect
JavaScript's Proxy object lets you intercept and redefine fundamental operations on another object — property reads, writes, deletions, function calls, and more. Reflect is its companion API that provides default implementations of those same operations. Together they unlock powerful metaprogramming patterns: validation layers, reactive systems, access control, and virtual objects — all without modifying the original object.
Three Building Blocks of Proxy & Reflect
Every Proxy interaction involves exactly three participants. Knowing each role prevents confusion when reading or writing proxy code:
{}, an array,
a class instance, or even another Proxy[[Get]], [[Set]]).Reflect.get() inside a trap to call the original operation
after your custom logic runs.Anatomy of a Proxy
Creating a Proxy takes exactly two arguments — the target and the handler. Here is the smallest possible example — an empty handler that passes every operation straight through to the target:
const target = { name: "Alice", age: 30 };
const handler = {
get(target, prop) {
console.log(`Reading "${prop}"`);
return Reflect.get(target, prop); // default behaviour
}
};
const proxy = new Proxy(target, handler);
proxy.name; // logs: Reading "name" → "Alice"
// ── Transparent proxy — no traps, passes everything through ───
const raw = { x: 10, y: 20 };
const p1 = new Proxy(raw, {}); // empty handler
console.log(p1.x); // 10
// ── get trap — intercept property reads ──────────────────────
const p2 = new Proxy(raw, {
get(target, prop, receiver) {
console.log(`get: ${prop}`);
return Reflect.get(target, prop, receiver);
}
});
p2.x; // logs: get: x → 10
// ── set trap — intercept property writes ─────────────────────
const p3 = new Proxy({}, {
set(target, prop, value) {
if (typeof value !== "number") throw new TypeError("Numbers only!");
return Reflect.set(target, prop, value);
}
});
p3.score = 42; // ✅ OK
p3.score = "hello"; // ❌ TypeError: Numbers only!
The 13 Proxy Traps
A handler object can define up to 13 trap methods. Each trap intercepts
one internal JavaScript operation. The most frequently used traps are
get, set, and
has:
proxy.prop reads
proxy.prop = val
prop in proxy
delete proxy.prop
Object.keys(proxy)
Object.getOwnPropertyDescriptor()
Object.defineProperty()
new proxy()
Object.getPrototypeOf(proxy)
Object.setPrototypeOf(proxy, …)
Object.isExtensible(proxy)
Object.preventExtensions(proxy)
const data = { name: "Bob", _secret: "hidden" };
const safeProxy = new Proxy(data, {
// 1. get — block private props (starting with _)
get(target, prop) {
if (prop.startsWith("_")) throw new Error("Access denied");
return Reflect.get(target, prop);
},
// 2. set — type-check before writing
set(target, prop, value) {
if (prop === "name" && typeof value !== "string")
throw new TypeError("name must be a string");
return Reflect.set(target, prop, value);
},
// 3. has — hide private props from 'in' operator
has(target, prop) {
if (prop.startsWith("_")) return false;
return Reflect.has(target, prop);
},
// 4. deleteProperty — protect certain keys
deleteProperty(target, prop) {
if (prop === "name") throw new Error("Cannot delete name");
return Reflect.deleteProperty(target, prop);
}
});
safeProxy.name; // ✅ "Bob"
safeProxy._secret; // ❌ Error: Access denied
"_secret" in safeProxy; // false (hidden)
The Reflect API
Reflect is a built-in object (not a
constructor — you cannot use new Reflect()) that provides static methods
corresponding to every JavaScript internal operation. Its two main purposes are:
receiver argument for getters/setters
that rely on prototypes — something a plain target[prop] access does not do.
(2) It returns a boolean (true/false) for operations like
set and deleteProperty, which is what traps are expected to return to
signal success or failure to the runtime.
const obj = { a: 1, b: 2 };
// Reflect.get — like obj[prop] but receiver-aware
Reflect.get(obj, "a"); // 1
// Reflect.set — returns true/false (unlike direct assignment)
Reflect.set(obj, "c", 3); // true
// Reflect.has — like 'prop in obj'
Reflect.has(obj, "a"); // true
// Reflect.deleteProperty — like delete obj.prop
Reflect.deleteProperty(obj, "b"); // true
// Reflect.ownKeys — all own keys (string + symbol)
Reflect.ownKeys(obj); // ["a", "c"]
// Reflect.apply — like fn.apply(thisArg, args)
const sum = (a, b) => a + b;
Reflect.apply(sum, null, [3, 4]); // 7
// Reflect.construct — like new Target(...args)
class Point { constructor(x, y) { this.x = x; this.y = y; } }
Reflect.construct(Point, [1, 2]); // Point {x:1, y:2}
| Operation | Old Way | Reflect Equivalent | Returns | Notes |
|---|---|---|---|---|
| Read | obj[prop] |
Reflect.get(obj, prop) |
value | Receiver-aware for getters |
| Write | obj[prop] = val |
Reflect.set(obj, prop, val) |
boolean | Returns false in strict mode failures |
| Check | prop in obj |
Reflect.has(obj, prop) |
boolean | Walks prototype chain |
| Delete | delete obj.prop |
Reflect.deleteProperty(obj, prop) |
boolean | No TypeError in non-strict mode |
| Call fn | fn.apply(this, args) |
Reflect.apply(fn, this, args) |
return val | Safer — fn.apply can be overridden |
| Construct | new Fn(...args) |
Reflect.construct(Fn, args) |
instance | Supports optional newTarget |
Revocable Proxies
Proxy.revocable() creates a proxy that
can be permanently disabled. After calling revoke(), any
further access to the proxy throws a TypeError. This is useful for temporarily
granting access to sensitive data, then revoking it when a task completes:
// ❌ PROBLEM: once you share an object, you cannot take it back
const secret = { token: "abc-123" };
someLibrary.use(secret); // library now holds a direct reference forever
// ✅ BETTER: pass a revocable proxy, revoke when done
const { proxy, revoke } = Proxy.revocable(secret, {});
someLibrary.use(proxy);
revoke(); // proxy is now dead — any access throws TypeError
const { proxy, revoke } = Proxy.revocable({ data: 42 }, {
get(target, prop) {
console.log(`Accessing ${prop}`);
return Reflect.get(target, prop);
}
});
console.log(proxy.data); // logs: Accessing data → 42
revoke(); // disable the proxy
try {
proxy.data; // ❌ TypeError: Cannot perform 'get'
} catch (e) {
console.error(e.message);
}
Key Method Reference
These are the Proxy traps and Reflect methods you'll reach for in virtually every real-world use case. Bookmark this list:
target. Every operation
on
the proxy first passes through the matching trap in handler, if
defined.proxy.prop,
proxy["prop"], destructuring, and Reflect.get.
The receiver is the object the operation was originally
directed at (important for inheritance).
true on success or false on failure — returning
nothing causes a TypeError in strict mode.in operator. Return a boolean.
Useful for hiding properties from enumeration while keeping them accessible via
direct reads.proxy(),
proxy.call(), proxy.apply(). The target must be a
callable (function); otherwise a TypeError is thrown.
{ proxy, revoke }. Calling
revoke() permanently disables the proxy. Any subsequent access throws a
TypeError. Perfect for temporary capability grants.
target[prop] access — they correctly forward the
receiver and return the boolean results that traps are expected to
return.
Object.keys() it also includes non-enumerable
and Symbol-keyed properties.Real-World Use Cases
Here are the patterns you'll encounter Proxy used for in real JavaScript projects and frameworks:
set trap to validate every property write
against a schema — type, range, or format — before it reaches the object._) using get, set, and
has traps.
apply trap that caches
results by arguments — returning cached values instantly on repeated calls.undefined — useful for mocking deeply nested API responses in
tests.
Try It — Live Editor
Experiment with Proxy below. The demo builds a reactive counter object — any write to it automatically logs the change. Edit the handler and run to see your result.
Common Patterns
Three patterns you will see repeatedly in real codebases that use Proxy:
// Return a default value for any missing property instead of undefined
function withDefaults(target, defaults) {
return new Proxy(target, {
get(t, prop, receiver) {
return Reflect.has(t, prop)
? Reflect.get(t, prop, receiver)
: defaults[prop];
}
});
}
const config = withDefaults({ theme: "dark" }, { theme: "light", lang: "en" });
config.theme; // "dark" (from target)
config.lang; // "en" (from defaults)
function memoize(fn) {
const cache = new Map();
return new Proxy(fn, {
apply(target, thisArg, args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
console.log("cache hit");
return cache.get(key);
}
const result = Reflect.apply(target, thisArg, args);
cache.set(key, result);
return result;
}
});
}
const slowSquare = n => { return n * n; }; // imagine it's slow
const fastSquare = memoize(slowSquare);
fastSquare(9); // computed: 81
fastSquare(9); // cache hit → 81
function reactive(obj, onChange) {
return new Proxy(obj, {
set(target, prop, value) {
const old = target[prop];
const ok = Reflect.set(target, prop, value);
if (ok && old !== value) onChange(prop, old, value);
return ok;
}
});
}
const store = reactive({ count: 0, name: "App" }, (prop, old, val) => {
console.log(`[CHANGE] ${prop}: ${old} → ${val}`);
// trigger UI re-render here
});
store.count++; // [CHANGE] count: 0 → 1
store.name = "MyApp"; // [CHANGE] name: App → MyApp
prop in proxy?Reflect.set() inside a set trap
instead of writing target[prop] = value directly?- A Proxy wraps a target object and intercepts its internal operations via handler traps — without modifying the original object.
- There are 13 traps. The most common are
get,set,has,deleteProperty,apply, andownKeys. - Always call the matching Reflect method inside a trap to perform the
default operation — it correctly handles the
receiverand returns the boolean that traps must return. - The
settrap must returntrueon success (or callReflect.set()which does this for you) — failing to return truthy causes aTypeErrorin strict mode. - Proxy.revocable() creates a proxy with a paired
revoke()function. After revocation all access throws a TypeError — ideal for temporary capability delegation. - Common real-world uses: schema validation, reactive/observable state (Vue 3 reactivity), access control, property logging, memoization, and default values.
- Proxy adds a small per-operation overhead. It is negligible in typical application code but benchmark before using in performance-critical loops.
- You cannot proxy primitive values — only objects, arrays, functions, and other proxies.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.