Proxies and Reflect
How `Proxy` intercepts operations through traps like `get`/`set`/`has`/`deleteProperty`, how `Reflect` gives traps a safe fallback, and real uses.
Proxies and Reflect
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A `Proxy` wraps a target object and lets you intercept fundamental operations on it — reading a property, setting one, checking `in`, deleting a key — through a set of functions called traps, without the object's own code ever knowing it's being watched.
- Every operation you don't define a trap for falls through to the target unchanged — a `Proxy` with an empty handler behaves exactly like the object it wraps, so you only write the traps for the behavior you actually want to change.
- `Reflect` is a built-in object with one method per trap (`Reflect.get`, `Reflect.set`, `Reflect.has`, ...) that performs the operation's normal default behavior — calling it from inside a trap is how you forward to "what would have happened anyway" instead of re-implementing property lookup yourself and getting the edge cases wrong.
- Real systems reach for this to validate writes before they happen, log or audit every read and write to an object, or build a reactivity system that tracks which properties got read so it knows what to re-run when one of them later changes — Vue 3's reactivity system is built on exactly this mechanism.
- A `Proxy` only intercepts operations that go through it — code that already holds a direct reference to the original target object bypasses the proxy entirely, which matters when you're deciding what to hand out and what to keep private.
The problem: intercepting what happens to an object
Most of what you do with an object is direct: you read a property, you get back whatever’s stored there; you set one, it changes. That works fine until you need something to happen around those operations instead of just as them — checking a value before it’s allowed to be set, recording every read for later, or noticing when a value changed at all. Short of rewriting every single property into a getter/setter pair by hand (and guessing in advance which properties you’ll ever need to guard), plain objects give you no way to hook into “someone just read or wrote a property” as a general event.
Proxy is the language’s answer: a wrapper object that sits in front of a
target object and lets you intercept the fundamental operations performed
on it — not just property reads and writes, but checking in, deleting a
key, even calling the object as a function, if the target is one. Code that
interacts with the proxy behaves, as far as it’s concerned, like it’s
interacting with the real object. Underneath, your own functions — traps —
get a chance to run first.
Traps, and the handler object
A Proxy is built from two things: the target object you’re wrapping, and
a handler object whose methods are the traps.
const user = { name: 'Ada', age: 37 };
const guarded = new Proxy(user, {
get(target, prop) {
console.log(`reading ${String(prop)}`);
return target[prop];
},
set(target, prop, value) {
if (prop === 'age' && typeof value !== 'number') {
throw new TypeError('age must be a number');
}
target[prop] = value;
return true;
},
});
guarded.name; // logs "reading name", returns "Ada"
guarded.age = 'old'; // throws TypeError
get fires on every property read, set on every write, and there’s a
matching trap for most other fundamental operations: has for the in
operator, deleteProperty for delete, ownKeys for
Object.keys-style enumeration, and more. Leave a trap out of the handler
and that operation just passes through to the target unmodified — a
Proxy with {} as its handler is functionally identical to the object it
wraps.
Why Reflect exists
Inside a trap, you often want to let the operation actually happen — just
after your own logic runs. You could write target[prop] = value
directly, and for the simple cases it works. The trouble is that property
assignment in JavaScript has edge cases around inherited setters and the
exact receiver the operation should apply to, and reimplementing all of
that by hand inside every trap is exactly the kind of subtly-wrong code
nobody wants to maintain.
Reflect is a built-in object with one method per trap —
Reflect.get, Reflect.set, Reflect.has, Reflect.deleteProperty, and
so on — each of which performs that operation’s real default behavior,
correctly, every time. Calling Reflect.set(target, prop, value) inside a
set trap means “now actually do the assignment, the way the engine
would’ve done it anyway” — you get to add behavior around the operation
without reimplementing the operation itself.
const logged = new Proxy(user, {
get(target, prop, receiver) {
console.log(`get: ${String(prop)}`);
return Reflect.get(target, prop, receiver);
},
});
What this is actually for
Three use cases come up repeatedly. Validation — reject a set before
it happens, the way the age example above does, so invalid data never
lands on the object at all. Logging and auditing — record every read or
write to a sensitive object without changing a single line of the code that
uses it. And reactivity — track which properties get read while some
piece of code runs, so you know exactly what to re-run later if one of
those properties changes. That last one is worth naming directly: Vue 3’s
reactivity system is built on wrapping reactive state in a Proxy, using
get to record dependencies and set to trigger updates. This lesson
isn’t teaching Vue — the point is just that “intercept reads and writes on
a plain object” is a real, production-grade technique, not a toy.
How the embedded video fits in
The embedded video covers both halves of this lesson directly: how a
Proxy’s traps intercept object operations, and how Reflect pairs with
them to forward default behavior cleanly — which maps straight onto the
set-trap-plus-Reflect.set pattern above. The “go deeper” video narrows
in on Proxy alone, with a validation-flavored example, if you want a
second pass focused just on the trap side before layering Reflect back
in.
Where this fits in the path
This follows symbols directly on purpose: a well-known symbol is a
narrow, per-property hook into one specific built-in behavior, and a
Proxy generalizes that same idea — intercepting operations before the
engine’s default behavior runs — across an entire object at once. Once you
can see both as instances of the same underlying idea, metaprogramming in
JavaScript stops looking like a grab-bag of unrelated tricks.
Check yourself
What does a `Proxy` actually wrap, and what happens for an operation you didn't define a trap for?
A `Proxy` wraps a target object and a handler object full of trap functions. Any operation performed on the proxy that has a matching trap runs that trap instead of touching the target directly; any operation without a matching trap falls through to the target's normal, default behavior unchanged.
Inside a `set` trap, why would you call `Reflect.set(target, prop, value)` instead of just writing `target[prop] = value`?
For simple cases they behave the same, but `Reflect.set` correctly forwards the receiver and handles edge cases around inherited accessors and non-writable properties the same way the engine's own default assignment behavior would. Writing `target[prop] = value` by hand works for the common case but can silently diverge from default semantics in those edge cases — `Reflect` exists specifically so a trap can delegate to "the real thing" instead of a hand-rolled approximation of it.
Give one concrete reason you'd reach for a `Proxy` instead of just writing getter/setter methods directly on an object?
A `Proxy` can intercept properties you don't know about ahead of time — any key, including ones added later — with a single pair of traps, where getters/setters have to be defined one property at a time and only work for properties you anticipated. That makes proxies a better fit for generic validation, logging, or reactivity layers that need to watch an object's shape without knowing what that shape will be in advance.
What's the catch with using a `Proxy` to restrict access to an object's data?
The restriction only applies to code that goes through the proxy. If any code — including your own, by accident — still holds a reference to the original target object, it can read and write it directly, completely bypassing every trap. A `Proxy` is a wrapper around access patterns, not a security boundary around the underlying object itself.
How does a framework's reactivity system use the ideas behind `Proxy` and `Reflect`, at a conceptual level?
It wraps reactive state in a `Proxy`, and uses the `get` trap to record which property a piece of rendering code read while it ran — building up a map of "this code depends on this property." The `set` trap then notices when one of those properties changes and re-runs only the code that depended on it, instead of re-checking everything. `Reflect` is what the traps use internally to still perform the actual read or write once the tracking bookkeeping is done.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.