JavaScript Proxy Explained: Handlers, Traps and Intercepting Object Operations
Learn JavaScript Proxy from the ground up: new Proxy(target, handler), transparent forwarding, get and set traps for defaults, validation and typo detection, has, deleteProperty and ownKeys for hiding properties, apply and construct traps for functions and classes, and Proxy.revocable.
kvi5hnuCode Sprout team member6 min readOn this page
A Proxy is an object that stands in for another object, the target, and lets you intercept the fundamental operations performed on it: reading and writing properties, checking in, deleting, listing keys, calling, constructing. Each intercepted operation goes to a function you write called a trap. Proxies power real tools: Vue's reactivity system, MobX, Immer's copy-on-write drafts, mocking libraries, and API clients whose methods are generated on the fly.
const proxy = new Proxy(target, handler);
- target: the object (or function) being wrapped. Must be an object;
new Proxy(1, {})throws aTypeError. - handler: an object whose methods are the traps. Each trap is named after one of the 13 internal operations listed in article 104.

An empty handler forwards everything
With no traps, a proxy is transparent: every operation passes straight through to the target.
const target = { name: "Ana" };
const proxy = new Proxy(target, {});
proxy.age = 30; // written to the target
console.log(target, proxy.name, proxy === target);
console.log(Array.isArray(new Proxy([1, 2], {})), typeof new Proxy(() => {}, {}));
{ name: 'Ana', age: 30 } Ana false
true function
The proxy is a different object from the target (proxy !== target), but it behaves like it. A proxy of an array is still an array for Array.isArray, and a proxy of a function is callable. Proxy must be called with new, and there's no Proxy.prototype.
The get trap
get(target, key, receiver) runs on every property read, including method lookups and symbol keys. Forward the default behavior with Reflect.get(target, key, receiver) (article 104), and add your own logic around it.
Default values
const tally = new Proxy({}, {
get(target, key, receiver) {
return Reflect.has(target, key) ? Reflect.get(target, key, receiver) : 0;
},
});
tally.apples++;
tally.apples++;
console.log(tally.apples, tally.pears);
2 0
Catching typos
Reading a misspelled property normally gives a silent undefined. A proxy can turn that into an immediate error:
function strictObject(obj) {
return new Proxy(obj, {
get(target, key, receiver) {
if (typeof key === "string" && !(key in target)) {
throw new ReferenceError(`Unknown property "${key}"`);
}
return Reflect.get(target, key, receiver);
},
});
}
const config = strictObject({ host: "localhost", port: 8080 });
console.log(config.port);
try {
console.log(config.prot);
} catch (err) {
console.log(err.name, err.message);
}
8080
ReferenceError Unknown property "prot"
The typeof key === "string" check matters: console.log, string conversion and other built-ins probe objects for symbol keys like Symbol.toPrimitive or Node's inspection symbol, and those probes shouldn't throw.
The set trap
set(target, key, value, receiver) runs on assignment. It must return true if the assignment succeeded. Returning false makes the assignment fail: silently in sloppy mode, with a TypeError in strict mode. Reflect.set returns exactly that boolean, so forwarding with return Reflect.set(...) is correct.
const person = new Proxy({}, {
set(target, key, value, receiver) {
if (key === "age" && (!Number.isInteger(value) || value < 0)) {
throw new TypeError(`Invalid age: ${value}`);
}
return Reflect.set(target, key, value, receiver);
},
});
person.age = 31;
try {
person.age = -5;
} catch (err) {
console.log(err.message);
}
console.log(person.age);
Invalid age: -5
31
A common bug is a set trap that does the work but forgets to return anything. undefined counts as false, so the assignment then throws in strict mode, which includes every ES module and class body.
Hiding properties: has, ownKeys, deleteProperty
To make "private" underscore properties invisible, you need several traps, because different operations reach the object through different internal methods:
const isHidden = (key) => typeof key === "string" && key.startsWith("_");
const user = new Proxy({ id: 1, name: "Ana", _passwordHash: "x9f2" }, {
get: (target, key, receiver) => (isHidden(key) ? undefined : Reflect.get(target, key, receiver)),
has: (target, key) => !isHidden(key) && Reflect.has(target, key),
ownKeys: (target) => Reflect.ownKeys(target).filter((key) => !isHidden(key)),
});
console.log(user._passwordHash, "_passwordHash" in user);
console.log(Object.keys(user), JSON.stringify(user), { ...user });
undefined false
[ 'id', 'name' ] {"id":1,"name":"Ana"} { id: 1, name: 'Ana' }
get covers reads, has covers the in operator, and ownKeys covers Object.keys, for...in, JSON and spread. Proxies are a weak privacy tool, though: the target still holds the data, and anyone with a reference to the target can read it. For real encapsulation, use private class fields (#passwordHash, article 71).
The deleteProperty(target, key) trap intercepts delete. It must also return a boolean:
const settings = new Proxy({ theme: "dark" }, {
deleteProperty(target, key) {
console.log(`refusing to delete "${key}"`);
return true; // report success, but keep the property
},
});
delete settings.theme;
console.log(settings.theme);
refusing to delete "theme"
dark
Function proxies: apply and construct
When the target is a function, two more traps become available:
apply(target, thisArg, args)for calls;construct(target, args, newTarget)fornew.
function add(a, b) {
return a + b;
}
const traced = new Proxy(add, {
apply(target, thisArg, args) {
console.log(`add(${args.join(", ")})`);
return Reflect.apply(target, thisArg, args);
},
});
console.log(traced(2, 3), traced.name, traced.length);
add(2, 3)
5 add 2
Properties like name and length pass through to the target, because there's no get trap. A construct trap can count instances, enforce a singleton or inject dependencies:
class Connection {
constructor(url) {
this.url = url;
}
}
let created = 0;
const TrackedConnection = new Proxy(Connection, {
construct(target, args, newTarget) {
created++;
return Reflect.construct(target, args, newTarget);
},
});
const a = new TrackedConnection("db://a");
new TrackedConnection("db://b");
console.log(created, a instanceof Connection, a.url);
2 true db://a
The construct trap must return an object, or it throws a TypeError.
A read-only view
Traps that throw give you an object that callers can read but not change. Unlike Object.freeze, the original stays mutable for whoever owns it, and the view always shows its current state:
function readOnly(obj) {
const refuse = () => {
throw new TypeError("This object is read-only");
};
return new Proxy(obj, {
set: refuse,
deleteProperty: refuse,
defineProperty: refuse,
setPrototypeOf: refuse,
});
}
const settings = { theme: "dark" };
const view = readOnly(settings);
console.log(view.theme);
try {
view.theme = "light";
} catch (err) {
console.log(err.message);
}
settings.theme = "light"; // the owner can still change it
console.log(view.theme);
dark
This object is read-only
light
Watching what built-in methods do
A proxy that logs every trap is a great learning tool. Building the handler from Object.getOwnPropertyNames(Reflect) creates one logging trap per internal operation, and each trap forwards to the matching Reflect method. Pass the proxy to a built-in method and you can watch exactly which operations it performs:
function spy(target, label) {
const handler = {};
for (const trap of Object.getOwnPropertyNames(Reflect)) {
handler[trap] = (...args) => {
const key = args[1];
const shown = trap === "apply" || trap === "construct" ? "" : `(${String(key)})`;
console.log(`${label}: ${trap}${shown}`);
return Reflect[trap](...args);
};
}
return new Proxy(target, handler);
}
const scores = spy([10, 20], "scores");
const doubled = scores.map((n) => n * 2);
console.log(doubled);
scores: get(map)
scores: get(length)
scores: get(constructor)
scores: has(0)
scores: get(0)
scores: has(1)
scores: get(1)
[ 20, 40 ]
The log reveals details that are hard to learn any other way:
mapreadslengthonce, up front.- It reads
constructorto decide what kind of array to create (theSymbol.specieslookup from article 103). - It checks
has(i)before eachget(i), which is why it skips the holes in sparse arrays (article 55).
All the traps
| Trap | Intercepts |
|---|---|
get / set | property reads / assignments |
has | key in proxy (and with) |
deleteProperty | delete proxy.key |
ownKeys | Object.keys, getOwnPropertyNames, getOwnPropertySymbols, Reflect.ownKeys, for...in, spread, JSON |
getOwnPropertyDescriptor / defineProperty | descriptor reads / Object.defineProperty (and, indirectly, some assignments) |
getPrototypeOf / setPrototypeOf | prototype reads (including instanceof) / changes |
isExtensible / preventExtensions | Object.isExtensible / preventExtensions, seal, freeze |
apply / construct | function calls / new (function targets only) |
Every trap is optional, and each receives the target as its first argument.
Proxy.revocable
Proxy.revocable(target, handler) returns { proxy, revoke }. After revoke() is called, every operation on the proxy throws a TypeError, and the proxy drops its references to the target and handler. Use it to hand out temporary access, for example to a plugin, and cut it off later:
const { proxy, revoke } = Proxy.revocable({ balance: 42 }, {});
console.log(proxy.balance);
revoke();
try {
proxy.balance;
} catch (err) {
console.log("after revoke:", err.name);
}
42
after revoke: TypeError
Common questions
Does a Proxy copy the target?
No. It wraps the same object; changes made through the proxy (without traps that prevent them) modify the target, and changes to the target are visible through the proxy.
Why use Reflect inside traps instead of target[key]?
Reflect methods perform exactly the default operation, including passing the receiver so getters and setters get the right this, and they return the success booleans that traps like set and deleteProperty must return.
Can I tell whether an object is a Proxy?
Not from standard JavaScript, by design: a proxy should be indistinguishable from an ordinary object. Node exposes util.types.isProxy for debugging.
Are proxies slow?
Every trapped operation calls a function, so a proxy is slower than direct property access. That's fine for configuration, validation and reactive state, but avoid them in hot inner loops.
Summary
new Proxy(target, handler)creates an object whose operations go through the handler's traps; missing traps forward to the target.getandsetintercept reads and writes: use them for defaults, typo detection, validation and logging.set,deletePropertyanddefinePropertymust returntruefor success; forward withReflectto get it right.- Hiding properties needs
get,hasandownKeystogether. - Function targets add
applyandconstructtraps. Proxy.revocableproduces a proxy that can be switched off permanently.
Practice Questions
What does this print?
const p = new Proxy({}, { get: (t, k) => `<${String(k)}>` });
console.log(p.title, p[1]);
Answer
<title> <1>. Every read goes through the get trap. Property keys are always strings or symbols, so p[1] arrives as the key "1".
Why does this assignment throw a TypeError in an ES module?
const p = new Proxy({}, {
set(t, k, v) {
t[k] = v;
},
});
p.x = 1;
Answer
The set trap returns undefined, which counts as false (failure). ES modules run in strict mode, where a failed assignment throws a TypeError. Return true, or forward with return Reflect.set(t, k, v).
Write a proxy that makes property reads case-insensitive, so that headers["content-type"] and headers["Content-Type"] both work.
Answer
function caseInsensitive(obj) {
const lower = Object.fromEntries(Object.entries(obj).map(([k, v]) => [k.toLowerCase(), v]));
return new Proxy(lower, {
get: (target, key, receiver) =>
Reflect.get(target, typeof key === "string" ? key.toLowerCase() : key, receiver),
});
}
const headers = caseInsensitive({ "Content-Type": "text/html" });
console.log(headers["content-type"], headers["CONTENT-TYPE"]);
A proxy defines only a get trap that hides _secret. Does Object.keys(proxy) include "_secret"?
Answer
Yes. Object.keys uses the ownKeys and getOwnPropertyDescriptor operations, not get, so the key still appears. To hide it from key listings, add an ownKeys trap.
Previous: The JavaScript Reflect API: Reflect.get, set, has, ownKeys, apply and construct
Next: JavaScript Proxy Patterns and Pitfalls: Reactivity, Negative Indexes, Invariants and Limits

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.