Proxy
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2016.
TheProxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object.
In this article
Description
TheProxy object allows you to create an object that can be used in place of the original object, but which may redefine fundamentalObject operations like getting, setting, and defining properties. Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs, and so on.
You create aProxy with two parameters:
target: the original object which you want to proxyhandler: an object that defines which operations will be intercepted and how to redefine intercepted operations.
For example, this code creates a proxy for thetarget object.
const target = { message1: "hello", message2: "everyone",};const handler1 = {};const proxy1 = new Proxy(target, handler1);Because the handler is empty, this proxy behaves just like the original target:
console.log(proxy1.message1); // helloconsole.log(proxy1.message2); // everyoneTo customize the proxy, we define functions on the handler object:
const target = { message1: "hello", message2: "everyone",};const handler2 = { get(target, prop, receiver) { return "world"; },};const proxy2 = new Proxy(target, handler2);Here we've provided an implementation of theget() handler, which intercepts attempts to access properties in the target.
Handler functions are sometimes calledtraps, presumably because they trap calls to the target object. The trap inhandler2 above redefines all property accessors:
console.log(proxy2.message1); // worldconsole.log(proxy2.message2); // worldProxies are often used with theReflect object, which provides some methods with the same names as theProxy traps. TheReflect methods provide the reflective semantics for invoking the correspondingobject internal methods. For example, we can callReflect.get if we don't wish to redefine the object's behavior:
const target = { message1: "hello", message2: "everyone",};const handler3 = { get(target, prop, receiver) { if (prop === "message2") { return "world"; } return Reflect.get(...arguments); },};const proxy3 = new Proxy(target, handler3);console.log(proxy3.message1); // helloconsole.log(proxy3.message2); // worldTheReflect method still interacts with the object through object internal methods — it doesn't "de-proxify" the proxy if it's invoked on a proxy. If you useReflect methods within a proxy trap, and theReflect method call gets intercepted by the trap again, there may be infinite recursion.
Terminology
The following terms are used when talking about the functionality of proxies.
- handler
The object passed as the second argument to the
Proxyconstructor. It contains the traps which define the behavior of the proxy.- trap
The function that defines the behavior for the correspondingobject internal method. (This is analogous to the concept oftraps in operating systems.)
- target
Object which the proxy virtualizes. It is often used as storage backend for the proxy. Invariants (semantics that remain unchanged) regarding object non-extensibility or non-configurable properties are verified against the target.
- invariants
Semantics that remain unchanged when implementing custom operations. If your trap implementation violates the invariants of a handler, a
TypeErrorwill be thrown.
Object internal methods
Objects are collections of properties. However, the language doesn't provide any machinery todirectly manipulate data stored in the object — rather, the object defines some internal methods specifying how it can be interacted with. For example, when you readobj.x, you may expect the following to happen:
- The
xproperty is searched up theprototype chain until it is found. - If
xis a data property, the property descriptor'svalueattribute is returned. - If
xis an accessor property, the getter is invoked, and the return value of the getter is returned.
There isn't anything special about this process in the language — it's just because ordinary objects, by default, have a[[Get]] internal method that is defined with this behavior. Theobj.x property access syntax simply invokes the[[Get]] method on the object, and the object uses its own internal method implementation to determine what to return.
As another example,arrays differ from normal objects, because they have a magiclength property that, when modified, automatically allocates empty slots or removes elements from the array. Similarly, adding array elements automatically changes thelength property. This is because arrays have a[[DefineOwnProperty]] internal method that knows to updatelength when an integer index is written to, or update the array contents whenlength is written to. Such objects whose internal methods have different implementations from ordinary objects are calledexotic objects.Proxy enable developers to define their own exotic objects with full capacity.
All objects have the following internal methods:
| Internal method | Corresponding trap |
|---|---|
[[GetPrototypeOf]] | getPrototypeOf() |
[[SetPrototypeOf]] | setPrototypeOf() |
[[IsExtensible]] | isExtensible() |
[[PreventExtensions]] | preventExtensions() |
[[GetOwnProperty]] | getOwnPropertyDescriptor() |
[[DefineOwnProperty]] | defineProperty() |
[[HasProperty]] | has() |
[[Get]] | get() |
[[Set]] | set() |
[[Delete]] | deleteProperty() |
[[OwnPropertyKeys]] | ownKeys() |
Function objects also have the following internal methods:
| Internal method | Corresponding trap |
|---|---|
[[Call]] | apply() |
[[Construct]] | construct() |
It's important to realize that all interactions with an object eventually boils down to the invocation of one of these internal methods, and that they are all customizable through proxies. This means almost no behavior (except certain critical invariants) is guaranteed in the language — everything is defined by the object itself. When you rundelete obj.x, there's no guarantee that"x" in obj returnsfalse afterwards — it depends on the object's implementations of[[Delete]] and[[HasProperty]]. Adelete obj.x may log things to the console, modify some global state, or even define a new property instead of deleting the existing one, although these semantics should be avoided in your own code.
All internal methods are called by the language itself, and are not directly accessible in JavaScript code. TheReflect namespace offers methods that do little more than call the internal methods, besides some input normalization/validation. In each trap's page, we list several typical situations when the trap is invoked, but these internal methods are called ina lot of places. For example, array methods read and write to array through these internal methods, so methods likepush() would also invokeget() andset() traps.
Most of the internal methods are straightforward in what they do. The only two that may be confusable are[[Set]] and[[DefineOwnProperty]]. For normal objects, the former invokes setters; the latter doesn't. (And[[Set]] calls[[DefineOwnProperty]] internally if there's no existing property or the property is a data property.) While you may know that theobj.x = 1 syntax uses[[Set]], andObject.defineProperty() uses[[DefineOwnProperty]], it's not immediately apparent what semantics other built-in methods and syntaxes use. For example,class fields use the[[DefineOwnProperty]] semantic, which is why setters defined in the superclass are not invoked when a field is declared on the derived class.
Constructor
Proxy()Creates a new
Proxyobject.
Note:There's noProxy.prototype property, soProxy instances do not have any special properties or methods.
Static methods
Proxy.revocable()Creates a revocable
Proxyobject.
Examples
>Basic example
In this example, the number37 gets returned as the default value when the property name is not in the object. It is using theget() handler.
const handler = { get(obj, prop) { return prop in obj ? obj[prop] : 37; },};const p = new Proxy({}, handler);p.a = 1;p.b = undefined;console.log(p.a, p.b); // 1, undefinedconsole.log("c" in p, p.c); // false, 37No-op forwarding proxy
In this example, we are using a native JavaScript object to which our proxy will forward all operations that are applied to it.
const target = {};const p = new Proxy(target, {});p.a = 37; // Operation forwarded to the targetconsole.log(target.a); // 37 (The operation has been properly forwarded!)Note that while this "no-op" works for plain JavaScript objects, it does not work for native objects, such as DOM elements,Map objects, or anything that has internal slots. Seeno private field forwarding for more information.
No private field forwarding
A proxy is still another object with a different identity — it's aproxy that operates between the wrapped object and the outside. As such, the proxy does not have direct access to the original object'sprivate elements.
class Secret { #secret; constructor(secret) { this.#secret = secret; } get secret() { return this.#secret.replace(/\d+/, "[REDACTED]"); }}const secret = new Secret("123456");console.log(secret.secret); // [REDACTED]// Looks like a no-op forwarding...const proxy = new Proxy(secret, {});console.log(proxy.secret); // TypeError: Cannot read private member #secret from an object whose class did not declare itThis is because when the proxy'sget trap is invoked, thethis value is theproxy instead of the originalsecret, so#secret is not accessible. To fix this, use the originalsecret asthis:
const proxy = new Proxy(secret, { get(target, prop, receiver) { // By default, it looks like Reflect.get(target, prop, receiver) // which has a different value of `this` return target[prop]; },});console.log(proxy.secret);For methods, this means you have to redirect the method'sthis value to the original object as well:
class Secret { #x = 1; x() { return this.#x; }}const secret = new Secret();const proxy = new Proxy(secret, { get(target, prop, receiver) { const value = target[prop]; if (value instanceof Function) { return function (...args) { return value.apply(this === receiver ? target : this, args); }; } return value; },});console.log(proxy.x());Some native JavaScript objects have properties calledinternal slots, which are not accessible from JavaScript code. For example,Map objects have an internal slot called[[MapData]], which stores the key-value pairs of the map. As such, you cannot trivially create a forwarding proxy for a map:
const proxy = new Proxy(new Map(), {});console.log(proxy.size); // TypeError: get size method called on incompatible ProxyYou have to use the "this-recovering" proxy illustrated above to work around this.
Validation
With aProxy, you can easily validate the passed value for an object. This example uses theset() handler.
const validator = { set(obj, prop, value) { if (prop === "age") { if (!Number.isInteger(value)) { throw new TypeError("The age is not an integer"); } if (value > 200) { throw new RangeError("The age seems invalid"); } } // The default behavior to store the value obj[prop] = value; // Indicate success return true; },};const person = new Proxy({}, validator);person.age = 100;console.log(person.age); // 100person.age = "young"; // Throws an exceptionperson.age = 300; // Throws an exceptionManipulating DOM nodes
In this example we useProxy to toggle an attribute of two different elements: so when we set the attribute on one element, the attribute is unset on the other one.
We create aview object which is a proxy for an object with aselected property. The proxy handler defines theset() handler.
When we assign an HTML element toview.selected, the element's'aria-selected' attribute is set totrue. If we then assign a different element toview.selected, this element's'aria-selected' attribute is set totrue and the previous element's'aria-selected' attribute is automatically set tofalse.
const view = new Proxy( { selected: null, }, { set(obj, prop, newVal) { const oldVal = obj[prop]; if (prop === "selected") { if (oldVal) { oldVal.setAttribute("aria-selected", "false"); } if (newVal) { newVal.setAttribute("aria-selected", "true"); } } // The default behavior to store the value obj[prop] = newVal; // Indicate success return true; }, },);const item1 = document.getElementById("item-1");const item2 = document.getElementById("item-2");// select item1:view.selected = item1;console.log(`item1: ${item1.getAttribute("aria-selected")}`);// item1: true// selecting item2 de-selects item1:view.selected = item2;console.log(`item1: ${item1.getAttribute("aria-selected")}`);// item1: falseconsole.log(`item2: ${item2.getAttribute("aria-selected")}`);// item2: trueValue correction and an extra property
Theproducts proxy object evaluates the passed value and converts it to an array if needed. The object also supports an extra property calledlatestBrowser both as a getter and a setter.
const products = new Proxy( { browsers: ["Firefox", "Chrome"], }, { get(obj, prop) { // An extra property if (prop === "latestBrowser") { return obj.browsers[obj.browsers.length - 1]; } // The default behavior to return the value return obj[prop]; }, set(obj, prop, value) { // An extra property if (prop === "latestBrowser") { obj.browsers.push(value); return true; } // Convert the value if it is not an array if (typeof value === "string") { value = [value]; } // The default behavior to store the value obj[prop] = value; // Indicate success return true; }, },);console.log(products.browsers);// ['Firefox', 'Chrome']products.browsers = "Safari";// pass a string (by mistake)console.log(products.browsers);// ['Safari'] <- no problem, the value is an arrayproducts.latestBrowser = "Edge";console.log(products.browsers);// ['Safari', 'Edge']console.log(products.latestBrowser);// 'Edge'Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-proxy-objects> |
Browser compatibility
Loading…
See also
- Proxies are awesome presentation by Brendan Eich at JSConf (2014)