CodeBlanks Logo Icon CodeBlanks

Proxy use cases

JavaScript course · Advanced · Lesson 64/100

Learn real proxy uses like validation, logging and tracing.

A validation proxy

One of the most common uses of Proxy is validation. By placing a condition inside the set trap, you make sure only valid values are written to a property.

const handler = {
  set(target, prop, value) {
    if (typeof value !== 'number') {
      throw new TypeError('number required');
    }
    return Reflect.set(target, prop, value);
  }
};

Here, assigning a non-number to age throws an error. The validation logic lives in one place, inside the proxy, so the same rule applies at every assignment site.

Logging and tracing proxies

Proxy is also handy for logging and tracing. Add a console.log line inside the get trap to record every property read, or inside the set trap to watch every assignment.

const handler = {
  get(target, prop) {
    console.log('read', prop);
    return Reflect.get(target, prop);
  }
};

This pattern is powerful for debugging, since you can see which property is accessed and when. After the log line you still apply the default behavior with Reflect, so the object keeps working as expected.

Exercise Write a validation proxy

Define an empty object named user. Inside a handler, write a set trap: if prop === 'age' and typeof value !== 'number', throw new TypeError('age must be a number'); otherwise return Reflect.set(target, prop, value). Create a proxy variable with new Proxy(user, handler). Assign proxy.age = 28 and log it with console.log(proxy.age).

Show example solution
const user = {};
const handler = {
  set(target, prop, value) {
    if (prop === 'age' && typeof value !== 'number') {
      throw new TypeError('age must be a number');
    }
    return Reflect.set(target, prop, value);
  }
};
const proxy = new Proxy(user, handler);
proxy.age = 28;
console.log(proxy.age);

Test yourself

  1. What does the set trap of a validation proxy do?

    • writes via Reflect.set but checks first
    • always returns true
    • ignores the value
    • only logs to the console
    Show answer

    writes via Reflect.set but checks first — Correct! A validation proxy checks the value first, then writes it with Reflect.set.

  2. Throw a validation error

    if (typeof value !== 'number') {
      ____;
    }
    Show answer
    if (typeof value !== 'number') {
      throw new TypeError('age must be a number');
    }
  3. Match the Proxy use cases

    validation
    blocks invalid value
    logging
    records access
    tracing
    notifies changes
    default
    returns via Reflect

All lessons in Advanced