Controlling object operations with Proxy

Proxy lets you create an object that wraps another object and intercepts the fundamental operations performed on it. MDN's description: it "enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object." The most common operations to take over are getting and setting values.

Each intercepted operation is handled by a trap—a handler function. The spec defines up to thirteen traps; validation, DOM updates and fetching typically need only a couple of them.

const myObj = {
  mykey: 'value'
}

console.log(myObj.mykey); // "gets" value of the key, outputs 'value'
myObj.mykey = 'updated'; // "sets" value of the key, makes it 'updated'

Constructing a proxy

The core pattern is a target object plus a handler object, both passed to the Proxy constructor:

const myObj = {
  mykey: 'value'
}

const handler = {
  get: function (target, prop) {
    return target[prop];
  },
  set: function (target, prop, value) {
    target[prop] = value;
    return true;
  }
}

const proxy = new Proxy(myObj, handler);

console.log(proxy.mykey); // "gets" value of the key, outputs 'value'
proxy.mykey = 'updated'; // "sets" value of the key, makes it 'updated'

The handler above uses get and set that simply pass values through unchanged. Operations on the proxy then forward to the original target, myObj.

Returning true from the set trap tells the proxy the assignment succeeded. Returning false blocks the write—a way to reject invalid data—and also produces a TypeError in the console.

Keeping the target out of reach

The target object remains available, so code can bypass the proxy and mutate it directly, skipping every trap. A common fix is to reference the target inside the constructor rather than exposing it:

const handler = {
  get: function (target, prop) {
    return target[prop];
  },
  set: function (target, prop, value) {
    target[prop] = value;
    return true;
  }
}

const proxy = new Proxy({
  mykey: 'value'
}, handler);

console.log(proxy.mykey); // "gets" value of the key, outputs 'value'
proxy.mykey = 'updated'; // "sets" value of the key, makes it 'updated'

Or create target and handler together inside the constructor:

const proxy = new Proxy({
  mykey: 'value'
}, {
  get: function (target, prop) {
    return target[prop];
  },
  set: function (target, prop, value) {
    target[prop] = value;
    return true;
  }
});

console.log(proxy.mykey); // "gets" value of the key, outputs 'value'
proxy.mykey = 'updated'; // "sets" value of the key, makes it 'updated'

Either arrangement works, and this inline form is the one used throughout the examples below.

Side effects on set: reversing input

A first small demo writes typed text into a proxy's value key and echoes it reversed into every element carrying a data-reverse attribute.

const reverse = new Proxy(
  {
    value: ''
  },
  {
    set: function (target, prop, value) {
      target[prop] = value;
      
      document.querySelectorAll('[data-reverse]').forEach(item => {
        let el = document.createElement('div');
        el.innerHTML = '\u{202E}' + value;
        item.innerText = el.innerHTML;
      });
      
      return true;
    }
  }
)

document.querySelector('input').addEventListener('input', e => {
  reverse.value = e.target.value;
});

The proxy has no get trap because nothing needs to happen on reads. In the set trap, the value is stored on value as usual, then a querySelectorAll collects all matching elements so several can be updated in one pass—the kind of binding commonly associated with a framework. The same approach would work against inputs for two-way binding.

The reversal is deliberately odd: a div is built in memory and given a string that begins with a Unicode decimal code forcing right-to-left rendering, so everything after it reads backwards. Each element's innerText receives that div's innerHTML. An input listener feeds the typed value into the proxy's value key.

Formatting and hiding data: a phone number field

Formatting a phone input as (123) 456-7890 while retaining the raw digits calls for two pieces of state: number for the formatted value and _clean for the unformatted one. The leading underscore follows the convention for a private member, exposed through a getter named clean.

const phone = new Proxy(
  {
    _clean: '',
    number: '',
    get clean() {
      return this._clean;
    }
  },
  {
    get: function (target, prop) {
      if (!prop.startsWith('_')) {
        return target[prop];
      } else {
        return 'entry not found!'
      }
    },
    set: function (target, prop, value) {
      if (!prop.startsWith('_')) {
        target._clean = value.replace(/\D/g, '').substring(0, 10);

        const sections = {
          area: target._clean.substring(0, 3),
          prefix: target._clean.substring(3, 6),
          line: target._clean.substring(6, 10)
        }

        target.number = 
          target._clean.length > 6 ? `(${sections.area}) ${sections.prefix}-${sections.line}` :
          target._clean.length > 3 ? `(${sections.area}) ${sections.prefix}` :
          target._clean.length > 0 ? `(${sections.area}` : '';

        document.querySelectorAll('[data-phone_number]').forEach(item => {
          if (item.tagName === 'INPUT') {
            item.value = target.number;
          } else {
            item.innerText = target.number;
          }
        });

        return true;
      } else {
        return false;
      }
    }
  }
);
{
  _clean: '',
  number: '',
  get clean() {
    return this._clean;
  }
},

The clean key returns _clean; treating it as a property rather than a method (phone.clean, not phone.clean()) makes it behave as a getter layered on top of the proxy's own get trap.

The get trap

get: function (target, prop) {
  if (!prop.startsWith('_')) {
    return target[prop];
  } else {
    return 'entry not found!'
  }
},

Any requested key that does not begin with an underscore is returned unchanged; a key that does start with one yields a "not found" string. The negative response is a design choice—an error or a side effect would serve equally well. Full protection of such a private member would also require handling traps such as defineProperty, deleteProperty and ownKeys, since any operation touching object keys can expose or modify it. How far to go depends on whether the proxy is for your own use or for others.

The set trap

set: function (target, prop, value) {
  if (!prop.startsWith('_')) {
    target._clean = value.replace(/\D/g, '').substring(0, 10);

    const sections = {
      area: target._clean.substring(0, 3),
      prefix: target._clean.substring(3, 6),
      line: target._clean.substring(6, 10)
    }

    target.number = 
      target._clean.length > 6 ? `(${sections.area}) ${sections.prefix}-${sections.line}` :
      target._clean.length > 3 ? `(${sections.area}) ${sections.prefix}` :
      target._clean.length > 0 ? `(${sections.area}` : '';

    document.querySelectorAll('[data-phone_number]').forEach(item => {
      if (item.tagName === 'INPUT') {
        item.value = target.number;
      } else {
        item.innerText = target.number;
      }
    });

    return true;
  } else {
    return false;
  }
}

The trap applies the same underscore check. The incoming value is reduced to digits only, stored in _clean, and then rebuilt into the formatted string on every keystroke, with substring capping the input at ten digits. A sections object splits a U.S. number into its parts, so the formatting pattern progresses as _clean grows. A querySelectorAll over data-phone_number elements runs a forEach: inputs get their value updated, everything else gets innerText. Success returns true; a key starting with an underscore returns false.

The listeners wire it together:

document.querySelectorAll('input[data-phone_number]').forEach(item => {
  item.addEventListener('input', (e) => {
    phone.number = e.target.value;
  });
});

document.querySelector('#get_data').addEventListener('click', (e) => {
  console.log(phone.number); // (123) 456-7890
  console.log(phone.clean); // 1234567890
});

The first block attaches an input listener to each matching input and pushes the current value—stripped of non-digits—into the proxy's number key. The second wires the button that logs both versions: the formatted value and phone.clean, which resolves through the getter to _clean.

An array as target, with rules

An array can serve as the target, though array behavior needs care. In the set trap, a push() arrives as an assignment to the length property, and custom functions defined on an object target have no direct equivalent. What the array buys is rule enforcement plus convenience reads.

const numbers = new Proxy([],
  {
    get: function (target, prop) {
      message.classList.remove('error');

      if (prop === 'sort') return [...target].sort((a, b) => a - b);
      if (prop === 'sum') return [...target].reduce((a, b) => a + b);
      if (prop === 'average') return [...target].reduce((a, b) => a + b) / target.length;

      if (prop === 'clear') {
        message.innerText = `${target.length} number${target.length === 1 ? '' : 's'} cleared!`;
        target.splice(0, target.length);
        collection.innerText = target;
      }

      return target[prop];
    },
    set: function (target, prop, value) {
      if (prop === 'length') return true;

      dataInput.value = '';
      message.classList.remove('error');

      if (!Number.isInteger(value)) {
        console.error('Data provided is not a number!');
        message.innerText = 'Data provided is not a number!';
        message.classList.add('error');
        return false;
      }

      if (target.includes(value)) {
        console.error(`Number ${value} has already been submitted!`);
        message.innerText = `Number ${value} has already been submitted!`;
        message.classList.add('error');
        return false;
      }

      target[prop] = value;
      collection.innerText = target;
      message.innerText = `Number ${value} added!`;

      return true;
  }
});

The set trap first checks whether the incoming property is length; if so it returns true and lets the operation proceed normally. It then grabs two page elements via querySelector: dataInput, an input cleared on every entry, and message, a feedback element reset from its error state on each entry.

The first if rejects non-numbers: it logs a console error, writes the same text into the message element, applies an error CSS class, and returns false, which also triggers the proxy's own console error. The second if rejects duplicates, with the message built as a template literal so the repeated value appears in it. If both checks pass, the value is stored, the collection element is updated to show the current array contents, and the message confirms what was added, followed by return true.

Named reads through get

get: function (target, prop) {
  message.classList.remove('error');

  if (prop === 'sort') return [...target].sort((a, b) => a - b);
  if (prop === 'sum') return [...target].reduce((a, b) => a + b);
  if (prop === 'average') return [...target].reduce((a, b) => a + b) / target.length;

  if (prop === 'clear') {
    message.innerText = `${target.length} number${target.length === 1 ? '' : 's'} cleared!`;
    target.splice(0, target.length);
    collection.innerText = target;
  }

  return target[prop];
},

Here the get trap handles property names that are not array methods at all: sort, sum, average and clear. Each returns a derived result without mutating the original array—the spread operator copies the target into a new array, then ordinary array methods run on it. clear is not a native array method, only a name chosen for the operation.

Each of these is triggered by a click listener, for example:

dataSort.addEventListener('click', () => {
  message.innerText = numbers.sort;
});
dataForm.addEventListener('submit', (e) => {
  e.preventDefault();
  numbers.push(Number.parseInt(dataInput.value));
});

dataSubmit.addEventListener('click', () => {
  numbers.push(Number.parseInt(dataInput.value));
});

dataSort.addEventListener('click', () => {
  message.innerText = numbers.sort;
});

dataSum.addEventListener('click', () => {
  message.innerText = numbers.sum;
});

dataAverage.addEventListener('click', () => {
  message.innerText = numbers.average;
});

dataClear.addEventListener('click', () => {
  numbers.clear;
});

Clicking sort writes whatever numbers.sort returns into the message element's innerText, the proxy intercepting what would ordinarily be a normal array lookup.

Address form with model-style binding

A form is the last example: the target holds one key per input, and every matching element on the page is kept in sync from the payload of a single object, collectable on demand.

const model = new Proxy(
  {
    name: '',
    address1: '',
    address2: '',
    city: '',
    state: '',
    zip: '',
    getData() {
      return {
        name: this.name || 'no entry!',
        address1: this.address1 || 'no entry!',
        address2: this.address2 || 'no entry!',
        city: this.city || 'no entry!',
        state: this.state || 'no entry!',
        zip: this.zip || 'no entry!'
      };
    }
  },
  {
    get: function (target, prop) {
      return target[prop];
    },
    set: function (target, prop, value) {
      target[prop] = value;
      
      if (prop === 'zip' && value.length === 5) {
        fetch(`https://api.zippopotam.us/us/${value}`)
          .then(response => response.json())
          .then(data => {
            model.city = data.places[0]['place name'];
            document.querySelector('[data-model="city"]').value = target.city;
          
            model.state = data.places[0]['state abbreviation'];
            document.querySelector('[data-model="state"]').value = target.state;
          });
      }
      
      document.querySelectorAll(`[data-model="${prop}"]`).forEach(item => {
        if (item.tagName === 'INPUT' || item.tagName === 'SELECT') {
          item.value = value;
        } else {
          item.innerText = value;
        }
      })
      
      return true;
    }
  }
);

The getData function returns the object, substituting "no entry!" wherever a value is an empty string—cleaner output than reading raw proxy state. The get trap passes values through, included for completeness.

The set trap stores the value, then checks whether the property being set is the zip code and whether its length is five. When both hold, it calls a fetch against an address finder API with that zip; returned values are written into the object, the city input, and the select element's state. It is a shortcut that pre-fills data the user can still change by hand.

Markup carries the binding key itself, for example on each input:

<input class="in__input" id="name" placeholder="name" />

A querySelectorAll finds every element with the matching data-model attribute and updates its value or its innerText—the same technique as the reverse-string demo—which is how a live preview of the completed address stays current. Because the attribute's value names the key, the proxy always knows what it is operating on, and the listener recovers the same key:

document.querySelector('main').addEventListener('input', (e) => {
  model[e.target.dataset.model] = e.target.value;
});

The listener attaches to every input inside the main container, and each input event writes into the proxy using the data-model value as the key. The result is a model-like layer over the DOM. Meanwhile the "get data" button is just a console log of the getData function:

getDataBtn.addEventListener('click', () => {
  console.log(model.getData());
});

Plain functions could reproduce all of these examples. The value of the proxy is that reacting to reads and writes—validating, protecting, driving the DOM, fetching related data—happens at the point where data is saved or retrieved, without a larger library. A UI-focused front-end developer can use the basics for a small widget; a deeper dive could go well past these demonstrations.