Skip to content
jshacks.dev
Fundamentals

Proxy and Reflect in JavaScript for Metaprogramming

A Proxy wraps an object and intercepts reads, writes, deletes and calls through traps, and Reflect forwards the default. See validation, defaults and catches.

9 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the JavaScript, GraphQL and Swagger logos.

Most of JavaScript's behavior is fixed: a property read finds a value or undefined, an assignment sets it, delete removes it. A Proxy lets you replace those rules for one object, and Reflect gives you the original rules as functions so you can add to them without rewriting them. The pair is how libraries build reactive state, validated models and fluent APIs. They are also easy to misuse: a proxy hides cost, breaks identity and trips on private fields. This post covers the traps you will use, the Reflect forwarding habit, the invariants that make a trap throw, and where a simpler tool is better. Output is from Node.js 24 as an ES module. The object model underneath is in the post on objects, and the descriptor flags that cause invariant errors are in the post on property descriptors.

A proxy and its handler

new Proxy(target, handler) returns an object that behaves like the target unless the handler defines a trap for the operation.

JavaScript
const target = { name: "Ada", visits: 1 };
const log = [];

const proxy = new Proxy(target, {
  get(object, key, receiver) {
    log.push(`get ${String(key)}`);
    return Reflect.get(object, key, receiver);
  },
  set(object, key, value, receiver) {
    log.push(`set ${String(key)}=${value}`);
    return Reflect.set(object, key, value, receiver);
  },
  has(object, key) {
    log.push(`has ${String(key)}`);
    return Reflect.has(object, key);
  },
  deleteProperty(object, key) {
    log.push(`delete ${String(key)}`);
    return Reflect.deleteProperty(object, key);
  },
});

proxy.visits += 1;
console.log(proxy.name, "name" in proxy);
delete proxy.name;

console.log(log);
console.log(target);
console.log(proxy === target, JSON.stringify(proxy));
Text
Ada true
[ 'get visits', 'set visits=2', 'get name', 'has name', 'delete name' ]
{ visits: 2 }
false {"visits":2}

Every operation went through the handler and then to the target. The += produced a read followed by a write, and the log shows both. The target was changed, since the proxy forwards to it, and the proxy and the target are different objects, so proxy === target is false. JSON.stringify(proxy) worked because it reads properties through the traps.

Why Reflect is used for forwarding

A trap could return object[key] directly, and it would work for plain data. It breaks with getters and inheritance, because the receiver, the object the operation was started on, is lost. Reflect.get(object, key, receiver) passes it along.

JavaScript
const user = {
  first: "Ada",
  last: "Lovelace",
  get full() {
    return `${this.first} ${this.last}`;
  },
};

const seen = [];

const naive = new Proxy(user, {
  get(object, key) {
    seen.push("naive " + String(key));
    return object[key];
  },
});

const proper = new Proxy(user, {
  get(object, key, receiver) {
    seen.push("proper " + String(key));
    return Reflect.get(object, key, receiver);
  },
});

console.log(naive.full);
console.log(proper.full);
console.log(seen);
Text
Ada Lovelace
Ada Lovelace
[ 'naive full', 'proper full', 'proper first', 'proper last' ]

Reading full through the naive proxy ran the getter with this set to the original object, so the inner reads of first and last skipped the proxy and were not logged. The proper version passed the receiver, so this was the proxy and every inner read was observed. Observers and reactive systems need the second behavior, since a dependency that is read inside a getter would otherwise go untracked.

Validation with set

A set trap can reject values before they reach the object. It returns true to accept, and in strict mode a falsy return throws a TypeError.

JavaScript
function validated(target, rules) {
  return new Proxy(target, {
    set(object, key, value, receiver) {
      const rule = rules[key];
      if (rule && !rule(value)) {
        throw new TypeError(`invalid value for ${String(key)}: ${JSON.stringify(value)}`);
      }
      return Reflect.set(object, key, value, receiver);
    },
  });
}

const person = validated(
  { age: 30, email: "[email protected]" },
  {
    age: (v) => Number.isInteger(v) && v >= 0 && v < 150,
    email: (v) => typeof v === "string" && v.includes("@"),
  },
);

person.age = 31;
console.log(person.age);

for (const bad of [() => (person.age = -1), () => (person.email = "nope")]) {
  try {
    bad();
  } catch (error) {
    console.log(error.name + ": " + error.message);
  }
}

const strictReject = new Proxy({}, { set: () => false });
try {
  strictReject.x = 1;
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
31
TypeError: invalid value for age: -1
TypeError: invalid value for email: "nope"
TypeError: 'set' on proxy: trap returned falsish for property 'x'

Good values passed through and bad ones were rejected with a message naming the field. The last example shows the false return: in strict mode, which modules use, the failed assignment throws. A trap that forgets to return a value, as in set(...) { object[key] = value; }, returns undefined, which counts as failure, so always return the Reflect.set result or true.

Defaults and computed properties

A get trap can supply values for properties that do not exist, which suits counters, default dictionaries and dynamic APIs.

JavaScript
const counts = new Proxy({}, {
  get: (object, key) => (key in object ? object[key] : 0),
});

for (const word of "a b a c b a".split(" ")) {
  counts[word] += 1;
}
console.log({ ...counts });
console.log(counts.zzz);

function negativeIndex(array) {
  return new Proxy(array, {
    get(object, key, receiver) {
      const index = typeof key === "string" && /^-\d+$/.test(key) ? object.length + Number(key) : key;
      return Reflect.get(object, index, receiver);
    },
  });
}

const list = negativeIndex(["a", "b", "c"]);
console.log(list[-1], list[-3], list[0], list.length);

const api = new Proxy({}, {
  get: (_, resource) => (id) => `GET /${String(resource)}/${id}`,
});
console.log(api.users(7), api.orders("abc"));
Text
{ a: 3, b: 2, c: 1 }
0
c a a 3
GET /users/7 GET /orders/abc

The counter returned zero for unseen keys, so += 1 worked without an initialization step. The array proxy added Python-style negative indexes, which the language later added as the at() method, covered in the at() post. The third example is the basis of dynamic clients: any property name becomes a function, with no method defined in advance.

Function proxies: apply and construct

Proxies can wrap functions, and the apply and construct traps intercept calls and new expressions.

JavaScript
function slowSquare(n) {
  return n * n;
}

const calls = [];

const traced = new Proxy(slowSquare, {
  apply(fn, thisArg, args) {
    calls.push(args);
    return Reflect.apply(fn, thisArg, args);
  },
});

console.log(traced(4), traced(5));
console.log(calls);

class Point {
  constructor(x) {
    this.x = x;
  }
}

const Counted = new Proxy(Point, {
  construct(Class, args, newTarget) {
    console.log("constructing with", args);
    return Reflect.construct(Class, args, newTarget);
  },
});

const point = new Counted(3);
console.log(point.x, point instanceof Point);
Text
16 25
[ [ 4 ], [ 5 ] ]
constructing with [ 3 ]
3 true

The traced function recorded each call and returned the right result, which is the basis of memoization wrappers, retry decorators and test spies. The constructor proxy ran code before creating an instance, and the result was a normal Point.

Invariants: where a trap is not allowed to lie

A proxy may not misreport a property that the target has made permanent. The engine checks, and throws when a trap breaks the rule.

JavaScript
const target = {};
Object.defineProperty(target, "fixed", { value: 1, writable: false, configurable: false });

const liar = new Proxy(target, {
  get: () => 2,
  has: () => false,
  deleteProperty: () => true,
});

for (const run of [() => liar.fixed, () => "fixed" in liar, () => delete liar.fixed]) {
  try {
    console.log(run());
  } catch (error) {
    console.log(error.name + ": " + error.message);
  }
}
Text
TypeError: 'get' on proxy: property 'fixed' is a read-only and non-configurable data property on the proxy target but the proxy did not return its actual value (expected '1' but got '2')
TypeError: 'has' on proxy: trap returned falsish for property 'fixed' which exists in the proxy target as non-configurable
TypeError: 'deleteProperty' on proxy: trap returned truish for property 'fixed' which is non-configurable in the proxy target

Each trap contradicted a non-configurable, non-writable property, and each call threw a TypeError that spells out the invariant. These checks keep the language's guarantees intact: code that froze an object can rely on it even if a proxy sits in the way. If you see one of these errors, the trap is returning something other than the target's real value for a locked property.

Revocable proxies

Proxy.revocable() returns a proxy and a function that disables it, which suits handing out temporary access.

JavaScript
const { proxy, revoke } = Proxy.revocable({ secret: 42 }, {});

console.log(proxy.secret);
revoke();

try {
  console.log(proxy.secret);
} catch (error) {
  console.log(error.name + ": " + error.message);
}

console.log(typeof proxy);
Text
42
TypeError: Cannot perform 'get' on a proxy that has been revoked
object

After revocation, every operation throws. The target stays alive and unchanged, and only the wrapper is dead, so you can give a callback access for the duration of a call and cut it off afterward.

The catches

A proxy is not transparent. Private class fields live on the real object, so a method that touches #field fails when called through a proxy, as shown in the post on private fields. Built-ins with internal slots, such as Map, Set and Date, throw when their methods are called with a proxy as this, and the fix is to bind the method to the target in a get trap. Identity comparisons and WeakMap lookups use the proxy, not the target, so the two are different keys. And every operation pays for a function call, so a proxy on a hot object costs more than a plain one, which is why frameworks proxy sparingly and cache.

JavaScript
const map = new Map([["a", 1]]);
const proxied = new Proxy(map, {});

try {
  proxied.get("a");
} catch (error) {
  console.log(error.name + ": " + error.message);
}

const bound = new Proxy(map, {
  get(object, key) {
    const value = Reflect.get(object, key, object);
    return typeof value === "function" ? value.bind(object) : value;
  },
});

console.log(bound.get("a"), bound.size);
Text
TypeError: Method Map.prototype.get called on incompatible receiver #<Map>
1 1

The plain proxy over a Map failed because get ran with the proxy as this, and Map methods need the real object. Binding functions to the target in the trap fixed it, at the cost of creating a bound function per access.

Testing code that uses proxies

A test for a proxy checks behavior through the proxy and also the target, since the whole point is that one wraps the other. Assert that valid writes reach the target, that invalid ones do not, and that reads return what the handler promises. Keep the handler in a named function so that you can test it without the wrapping, and add one test that proves the proxy does not break a feature you rely on, such as JSON.stringify or spread. If the code will be used with classes that have private fields, include a method that touches one, since that is the failure that arrives last and costs the most to find.

Where a proxy is the wrong tool

If you need a computed property, a getter is simpler and faster. If you need validation on a fixed set of fields, a class with setters is clearer. If you only want to freeze, Object.freeze() does it. Reach for a proxy when the set of keys is open, when you must observe reads and writes you do not control, or when you are building the layer that others will use, and document that the object is a proxy, since it will surprise whoever debugs it.

The behavior is defined in the specification under Proxy objects and Reflect, and MDN's pages on Proxy and Reflect list the traps and the invariants.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.