JavaScript Proxy Explained: All 13 Traps, Reflect and Real Use Cases
A JavaScript proxy wraps an object and lets you intercept what happens to it: reading a property, writing one, deleting one, checking keys, even calling a function. Learn the 13 traps, why Reflect belongs in every handler, eight tested use cases, and three traps of a different kind: private fields, invariants and an 11x slowdown.
- A JavaScript proxy is created with
new Proxy(target, handler); any trap you leave out forwards straight to the target. - Each trap has a matching
Reflectmethod with the same arguments, which performs the default behaviour correctly. - Proxying a class with
#privatefields broke method calls in our test until we bound methods to the target. - Reading a property through a proxy with a
gettrap was about 11 times slower than a plain object in Node 24.
Most JavaScript code just reads and writes object properties. A JavaScript proxy lets you step into the middle of those operations and decide what happens. Vue 3 uses proxies to detect changes and re-render, validation libraries use them to reject bad data, and test tools use them to record every call. Proxies are part of ES2015 and work in every modern browser and in Node.js.
All examples ran in Node.js v24.22.1, and the outputs are copied from the run.
What is a Proxy?
const proxy = new Proxy(target, handler);
The target is the real object. The handler is an object whose methods, called traps, intercept operations. With an empty handler, new Proxy(obj, {}), every operation passes straight through, and the proxy behaves like the target. The proxy is a new object: proxy === target is false, which matters if code compares identities.
All 13 proxy traps
| Trap | Intercepts |
|---|---|
get |
Reading a property: p.x, p[key] |
set |
Writing a property: p.x = 1 |
has |
The in operator |
deleteProperty |
The delete operator |
ownKeys |
Object.keys, for...in, JSON.stringify |
getOwnPropertyDescriptor |
Object.getOwnPropertyDescriptor |
defineProperty |
Object.defineProperty |
getPrototypeOf |
Object.getPrototypeOf, instanceof |
setPrototypeOf |
Object.setPrototypeOf |
isExtensible |
Object.isExtensible |
preventExtensions |
Object.preventExtensions |
apply |
Calling a function proxy: p(1, 2) |
construct |
new p() |
The first five cover nearly every real use. apply and construct only work when the target is a function, and typeof a function proxy is still "function".
Why use Reflect inside traps
Reflect is a built-in object with one method per trap, taking exactly the same arguments: Reflect.get(target, key, receiver), Reflect.set(target, key, value, receiver) and so on. Calling it performs the default operation, so a trap can add behaviour and then hand over. It is better than writing target[key] by hand because it passes the receiver along, which keeps getters and inheritance working, and because Reflect.set returns true or false, exactly what a set trap must return.
Use case 1: logging every read and write
const log = [];
const user = { name: "Asha", age: 30 };
const watched = new Proxy(user, {
get(t, k, r) { log.push(`get ${String(k)}`); return Reflect.get(t, k, r); },
set(t, k, v, r) { log.push(`set ${String(k)}=${v}`); return Reflect.set(t, k, v, r); },
});
watched.age += 1; watched.name;
// [ 'get age', 'set age=31', 'get name' ] user.age is now 31
watched.age += 1 triggered a read and then a write, and the change landed on the original object. This is the core of reactive frameworks: record which properties a component reads, and re-run it when one of them is written. String(k) matters because keys can be Symbols, which cannot be inserted into template strings directly.
Use case 2: validating writes
const validated = new Proxy({}, {
set(t, k, v) {
if (k === "age" && (!Number.isInteger(v) || v < 0))
throw new TypeError(`invalid age: ${v}`);
t[k] = v; return true;
},
});
validated.age = 41; // fine
validated.age = -5; // TypeError: invalid age: -5
validated.age = "old"; // TypeError: invalid age: old
Every assignment passes through one function, so the rule cannot be bypassed by any code holding the proxy. The set trap must return true for success; returning false throws a TypeError in strict mode.
Use case 3: default values for missing properties
const withDefaults = new Proxy({ theme: "dark" }, {
get: (t, k) => (k in t ? t[k] : "default"),
});
withDefaults.theme, withDefaults.font // 'dark' 'default'
Instead of undefined, missing settings fall back to a default. The same idea builds configuration objects and can throw on typos instead, which catches bugs like config.timout immediately.
Use case 4: negative array indexes
const arr = new Proxy([10, 20, 30], {
get(t, k, r) {
const i = Number(k);
return Number.isInteger(i) && i < 0 ? t[t.length + i] : Reflect.get(t, k, r);
},
});
arr[-1], arr[0], arr.length // 30 10 3
Property keys always arrive as strings, so the trap converts them. Everything that is not a negative integer, including length and array methods, is forwarded with Reflect. Modern code can use the built-in arr.at(-1) instead; this example shows how proxies can add syntax-like behaviour. More array tools are in our JavaScript array methods guide.
Use case 5: hiding private keys
const secret = new Proxy({ id: 1, _token: "x" }, {
has: (t, k) => !String(k).startsWith("_") && k in t,
ownKeys: (t) => Reflect.ownKeys(t).filter((k) => !String(k).startsWith("_")),
deleteProperty(t, k) { if (String(k).startsWith("_")) return false; delete t[k]; return true; },
});
"_token" in secret // false
Object.keys(secret) // [ 'id' ]
JSON.stringify(secret) // {"id":1}
delete secret._token // strict mode: TypeError 'deleteProperty' on proxy:
// trap returned falsish for property '_token'
ownKeys controlled what Object.keys and JSON.stringify saw, has hid the key from in, and deleteProperty refused the deletion. This hides data from casual inspection but is not real security: secret._token still returns "x" because we did not trap get. For truly private data, use class #private fields or a closure.
Use case 6: revocable access
const { proxy, revoke } = Proxy.revocable({ a: 1 }, {});
proxy.a // 1
revoke();
proxy.a // TypeError: Cannot perform 'get' on a proxy that has been revoked
A revocable proxy lets you hand an object to untrusted code, such as a plugin, and cut off access later. After revoke(), every operation throws.
Use case 7: wrapping a function
const fn = new Proxy((a, b) => a + b, {
apply(t, thisArg, args) {
const r = Reflect.apply(t, thisArg, args);
return `${args.join("+")}=${r}`;
},
});
fn(2, 3) // '2+3=5'
The apply trap sees every call with its arguments, which is how spies in testing libraries record calls, how memoisation wrappers cache results, and how timing wrappers measure functions.
Use case 8: classes with #private fields
class Counter { #n = 0; inc() { return ++this.#n; } }
const pc = new Proxy(new Counter(), {});
pc.inc();
// TypeError: Cannot read private member #n from an object whose class did not declare it
const pc2 = new Proxy(new Counter(), {
get(t, k) { const v = Reflect.get(t, k); return typeof v === "function" ? v.bind(t) : v; },
});
pc2.inc(), pc2.inc() // 1 2
This one surprises people. Calling pc.inc() runs inc with this set to the proxy, and the proxy does not have the private field, so even an empty handler failed. The same happens with built-ins that use internal slots, such as Map, Set and Date. Binding methods to the real target in the get trap fixed it. Our guide to the this keyword explains why the receiver matters, and our JavaScript classes guide covers private fields.
Invariants: rules a proxy cannot break
const frozen = Object.freeze({ k: 1 });
const liar = new Proxy(frozen, { get: () => 2 });
liar.k // TypeError
A proxy cannot lie about the target in ways that would break JavaScript’s guarantees. If a property is non-writable and non-configurable, as every property of a frozen object is, the get trap must return its real value. Our trap returned 2 instead of 1 and the engine threw a TypeError. Similar invariants apply to has, ownKeys, deleteProperty and the others.
The recursion bug: Reflect on the receiver
const rec = new Proxy({ a: 1 }, { get(t, k, r) { return Reflect.get(r, k); } });
rec.a // RangeError: Maximum call stack size exceeded
The third argument of get, the receiver, is usually the proxy itself. Reading from it calls the get trap again, forever. Always read from the target, Reflect.get(t, k, r), passing the receiver only as the third argument.
The performance cost
| Object | 10 million property reads |
|---|---|
| Plain object | 25.5 ms |
| Proxy with empty handler | 144.1 ms |
Proxy with a get trap calling Reflect |
286.9 ms |
Even an empty proxy was over five times slower, and a trap made it about 11 times slower, because the engine cannot apply its usual property-access optimisations. A few thousand reads per second will never notice. A hot loop over millions of items will, so unwrap the data or use plain objects in performance-critical code.
Where proxies are used in practice
- Reactivity: Vue 3 and MobX track reads and writes to update the UI.
- Validation and schemas: reject bad values at the moment they are assigned.
- Testing: spies and mocks that record calls, similar to the test doubles in other languages.
- API clients:
api.users.get(1)whereusersandgetare created on the fly by agettrap. - Immutable views: a read-only wrapper whose
setanddeletePropertytraps throw. For deep copies instead, see our JavaScript deep copy guide.
Final thoughts
A JavaScript proxy is a hook into the language itself. Use get and set for most needs, call Reflect on the target inside each trap, and remember the three gotchas we hit: private fields and built-ins need methods bound to the target, invariants on frozen objects cannot be faked, and every intercepted operation costs speed. Applied to configuration, validation, logging or reactive state, proxies replace a lot of repetitive getter and setter code with one small handler.
Frequently asked questions
What is a Proxy in JavaScript?
A Proxy wraps a target object and intercepts operations on it, such as reading, writing or deleting properties, through handler functions called traps. Operations without a trap go straight to the target.
What is the difference between Proxy and Reflect?
Proxy intercepts operations. Reflect performs the default version of each operation, with one method per trap and the same arguments, so traps use Reflect to forward the work correctly.
How many traps does a JavaScript Proxy have?
Thirteen: get, set, has, deleteProperty, ownKeys, getOwnPropertyDescriptor, defineProperty, getPrototypeOf, setPrototypeOf, isExtensible, preventExtensions, apply and construct.
Why does my Proxy break a class with private fields?
Methods run with this set to the proxy, which does not hold the private field. Bind methods to the real target in the get trap, or avoid proxying such classes.
Are JavaScript proxies slow?
They add overhead. In our Node 24 test, 10 million reads took 25 ms on a plain object, 144 ms through an empty proxy and 287 ms through a get trap.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.