Skip to content
jshacks.dev
Fundamentals

JavaScript Proxy set Trap Explained With Real Examples

The Proxy set trap intercepts every property write for validation, read-only views and change tracking. See the return rule, arrays and nested objects.

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

A plain object accepts anything you assign to it: a string where a number belongs, a negative age, a typo that creates a new property and leaves the real one unchanged. A Proxy with a set trap sits in front of the object and sees every write before it lands, so it can validate, convert, record, or refuse. The trap is the natural place for the checks that classes enforce through setters, applied to a plain object and to every key at once. The detail that trips most people is the return value: the trap must return true for a write that succeeded, and in strict mode a falsy return is an exception. This post covers the signature, validation, a read-only view, tracking array changes, nested objects that escape the trap, the rules the engine enforces, and the mistakes. The examples assume Node.js 24 in an ES module, where code is strict.

The signature and the return value

JavaScript
const target = {};

const proxy = new Proxy(target, {
  set(target, property, value, receiver) {
    console.log("write", String(property), value);
    return Reflect.set(target, property, value, receiver);
  },
});

proxy.name = "Ada";
proxy.age = 36;

console.log(target);
console.log(Object.keys(proxy));
Text
write name Ada
write age 36
{ name: 'Ada', age: 36 }
[ 'name', 'age' ]

The trap receives the target, the key, the new value and the receiver. Reflect.set(target, property, value, receiver) performs the real write and returns true or false, and returning its result is the correct way to finish. Writing straight to the target is possible, but then the trap owns the whole job, including the return value.

Forgetting to return

JavaScript
const careless = new Proxy({}, {
  set(target, property, value) {
    target[property] = value;
  },
});

try {
  careless.x = 1;
} catch (e) {
  console.log(e.name);
}

console.log(careless.x);
Text
TypeError
1

The write happened, since the assignment inside the trap ran, and then the engine saw an undefined return, treated it as false, and threw a TypeError in strict mode. In sloppy mode the failure is silent, which is worse: the code looks fine and runs in scripts and in the browser console, and throws only when it moves into a module. The value 1 is in the target either way. We write return Reflect.set(...) or return true as the last line of every set trap, and treat a trap without a return as a bug in review.

Validation

The classic use is rejecting bad data at the point of assignment.

JavaScript
const user = new Proxy({}, {
  set(target, property, value, receiver) {
    if (property === "age") {
      if (!Number.isInteger(value)) {
        throw new TypeError("age must be an integer");
      }
      if (value < 0 || value > 150) {
        throw new RangeError("age must be between 0 and 150");
      }
    }
    return Reflect.set(target, property, value, receiver);
  },
});

user.age = 36;
user.name = "Ada";

for (const bad of ["36", 36.5, -1, 200]) {
  try {
    user.age = bad;
  } catch (e) {
    console.log(e.name, "-", e.message);
  }
}

console.log(user.age, user.name);
Text
TypeError - age must be an integer
TypeError - age must be an integer
RangeError - age must be between 0 and 150
RangeError - age must be between 0 and 150
36 Ada

Every bad assignment throws, and the stored value stays at the last good one, 36. Throwing with a clear message is better than returning false, since a false return produces a generic message that names the trap and not the rule. The check lives in one function, so adding a second validated field is one more if, not one more setter. If the object has many fields with their own rules, keep the rules in a map from key to function, and call the right one from the trap.

Converting values

The trap can also change the value before it is stored.

JavaScript
const form = new Proxy({}, {
  set(target, property, value, receiver) {
    const clean = typeof value === "string" ? value.trim() : value;
    return Reflect.set(target, property, clean, receiver);
  },
});

form.email = "  [email protected] ";
form.count = 3;

console.log(JSON.stringify(form.email), form.count);
Text
"[email protected]" 3

The string was trimmed on the way in, and the number passed through. Using conversion in a trap means the stored value differs from the assigned one, so form.email = x; form.email === x can be false, which surprises readers. Keep conversions boring and document them next to the proxy.

A read-only view

Returning false refuses a write, and in strict mode that is an exception.

JavaScript
function readOnly(object) {
  return new Proxy(object, {
    set() {
      return false;
    },
    deleteProperty() {
      return false;
    },
    defineProperty() {
      return false;
    },
  });
}

const settings = readOnly({ theme: "dark" });

try {
  settings.theme = "light";
} catch (e) {
  console.log(e.name);
}

try {
  delete settings.theme;
} catch (e) {
  console.log(e.name);
}

console.log(settings.theme);
Text
TypeError
TypeError
dark

Blocking set alone is not enough, because Object.defineProperty() and delete are separate operations with their own traps. This is a shallow view: nested objects inside settings stay writable, which the nested section shows. For a plain flat object, Object.freeze() does the same job with no proxy and is the better choice. The proxy version earns its place when you want a read-only view of an object that someone else may still modify.

Arrays send two writes per push

An array write changes both an index and the length, and the trap sees each one.

JavaScript
const log = [];

const list = new Proxy([], {
  set(target, property, value, receiver) {
    log.push(`${String(property)}=${value}`);
    return Reflect.set(target, property, value, receiver);
  },
});

list.push("a");
list.push("b");
list.length = 0;

console.log(log.join(" "));
console.log(list.length);
Text
0=a length=1 1=b length=2 length=0
0

Each push() is an index write followed by a length write, and clearing the array is a length write. A trap that reacts to every write, such as one that sends an update to a screen, will fire twice per push unless it filters on length. We debounced those writes by recording that something changed and flushing once at the end of the current task, instead of reacting to each one.

Nested objects escape the trap

A proxy sees writes to its own properties and not to the objects those properties hold.

JavaScript
const changes = [];

const state = new Proxy({ user: { name: "Ada" }, count: 0 }, {
  set(target, property, value, receiver) {
    changes.push(String(property));
    return Reflect.set(target, property, value, receiver);
  },
});

state.count = 1;
state.user.name = "Grace";

console.log(changes);
console.log(state.user.name);
Text
[ 'count' ]
Grace

The write to state.user.name is a write to the inner object, and the proxy never saw it. To catch it, wrap nested objects as they are read, with a get trap that returns a proxy of each object value.

JavaScript
const seen = [];

function observe(object, path = "") {
  return new Proxy(object, {
    get(target, property, receiver) {
      const value = Reflect.get(target, property, receiver);
      return value !== null && typeof value === "object"
        ? observe(value, `${path}${String(property)}.`)
        : value;
    },
    set(target, property, value, receiver) {
      seen.push(`${path}${String(property)}`);
      return Reflect.set(target, property, value, receiver);
    },
  });
}

const tree = observe({ user: { name: "Ada" }, count: 0 });

tree.count = 1;
tree.user.name = "Grace";

console.log(seen);
Text
[ 'count', 'user.name' ]

Now the nested write is recorded with its path. The cost is a new proxy object on every read of a nested object, so tree.user === tree.user is false unless you cache the proxies in a WeakMap. This is how reactive state in front end frameworks works, and it is why they cache.

What the engine enforces

A trap cannot report success for a write that the target forbids.

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

const claims = new Proxy(locked, {
  set() {
    return true;
  },
});

try {
  claims.id = 2;
} catch (e) {
  console.log(e.name);
}

claims.id = 1;
console.log(locked.id);
Text
TypeError
1

Claiming a successful write of a different value to a non-writable, non-configurable property throws a TypeError. Writing the same value passes the check, since nothing would change. The engine enforces these invariants so that a proxy cannot make an object look different from the guarantees its target made.

A mistake we hit: setters on a prototype chain

When a proxy is the prototype of another object, writes to the child reach the proxy's trap with the child as the receiver.

JavaScript
const trap = new Proxy({}, {
  set(target, property, value, receiver) {
    console.log("trap saw", String(property), receiver === child);
    return Reflect.set(target, property, value, receiver);
  },
});

const child = Object.create(trap);

child.x = 1;

console.log(Object.hasOwn(child, "x"), Object.hasOwn(trap, "x"));
Text
trap saw x true
true false

The trap ran for a write on child, and because it passed the receiver to Reflect.set, the property landed on the child and not on the proxy's target. Writing target[property] = value instead would have stored it on the target and shared the value between all objects that inherit from the proxy. We found a shared-state bug of exactly that kind in a defaults object used as a prototype. Pass the receiver through unless you mean to write to the target.

Choosing between the write options

You wantUse
Validation on a plain objecta set trap
Validation on a classa setter
A frozen flat objectObject.freeze()
A read-only view of a changing objecta proxy with set, deleteProperty and defineProperty
Change notification on nested statea get and set pair that wraps nested objects
Reads with defaultsa [get trap](/library/javascript-proxy-get-trap)

Practical rules we follow

End every set trap with return Reflect.set(target, property, value, receiver) or an explicit true. Throw descriptive errors for validation, and return false only for a read-only view. Pass the receiver. Handle length and index writes in array proxies deliberately. Cache proxies of nested objects. And test the failure path: assign a bad value and assert both the error and that the old value is still there.

Where the set trap stops being the right tool

It sees writes through the proxy only, so code holding a reference to the target bypasses it. It does not see nested mutation without extra wrapping. It cannot validate a combination of fields until every field is written, so cross-field rules need a method such as validate() called at a known moment. It adds cost to every write. And it hides behavior from anyone reading code that uses the object, so a class with explicit setters is clearer for a fixed set of fields. The reference is in the MDN Proxy set handler page and the ECMAScript specification.

Taggedproxy
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.