Proxy & Reflect — JavaScript

new Proxy(target, handler) wraps the object target, and the traps (methods on handler) catch the operations on that object. The set(obj, prop, value) trap…

There is a guard at the office door. Anyone who wants to enter must pass the guard first: the guard writes down their name, checks their card, then lets them in or sends them away.

A Proxy works like that guard, but for an object. The office is the real object, and the visitors are the operations on that object, such as reading or changing a property. A Proxy wraps the object and catches every operation before it reaches the real object. Inside the Proxy you can record the operation, check it, then forward it or refuse it.

A first Proxy: a set trap for validation

This example wraps the object target in a Proxy that only accepts an age that is a number above 0:

const target = { age: 20 }

const student = new Proxy(target, {
  set(obj, prop, value) {
    if (typeof value !== 'number' || value <= 0) {
      throw new Error('Age must be a number above 0')
    }
    obj[prop] = value
    return true
  }
})

student.age = 25 // stored
student.age = -5 // Error: Age must be a number above 0

The result: student.age becomes 25. The value -5 is refused with an Error because of value <= 0, and the age stays 25. student.age = 'abc' is refused too, because its type isn't number. One note: a Proxy only guards operations that go through it. target.age = -5 writes directly to the real object, so it isn't checked at all.

The get trap: catching reads

This example makes a Proxy that gives its own answer for a property that doesn't exist:

const p = new Proxy({ name: 'Budi' }, {
  get(obj, prop) {
    return prop in obj ? obj[prop] : 'not found'
  }
})

console.log(p.name) // Budi
console.log(p.age) // not found

So a missing property isn't always undefined when it is read through a Proxy. Without this get trap, p.age is undefined. With this trap the result is 'not found', because the trap decides the result.

Reflect: forwarding an operation as it is

Reflect is an object built into JavaScript. Its methods have the same names as the traps, and each method does the built-in operation (what happens when there is no Proxy). This example records every read and write, then forwards it with Reflect:

const handler = {
  get(obj, prop) {
    console.log(`Reading ${prop}`)
    return Reflect.get(obj, prop)
  },
  set(obj, prop, value) {
    console.log(`Writing ${prop} = ${value}`)
    return Reflect.set(obj, prop, value)
  }
}

const user = new Proxy({}, handler)
user.name = 'Budi'     // Writing name = Budi
console.log(user.name) // Reading name, then Budi

Besides get and set, there are other traps, such as has (for the in operator) and deleteProperty (for delete).

⚠️ set traps that leak, or don't store anything

TL;DR: new Proxy(target, handler) wraps the object target, and the traps (methods on handler) catch the operations on that object. The set(obj, prop, value) trap (the real object, the property's name, the new value) catches writes to a property. Refuse a write with throw new Error(...), or store it with obj[prop] = value and then return true. The get(obj, prop) trap catches reads of a property, and whatever it returns becomes the result of the read. Reflect.get and Reflect.set run the built-in operation (what happens when there is no Proxy), so a trap can forward an operation with return Reflect.set(obj, prop, value).

⚡ A guard in front of an object

Write:

const student = new Proxy(target, {
  set(obj, prop, value) {
    if (typeof value !== 'number' || value <= 0) {
      throw new Error('Age must be a number above 0')
    }
    obj[prop] = value
    return true
  }
})

student.age = -5 // Error

Meaning: A Proxy wraps the object target and catches every operation before it reaches that real object, like a guard at an office door. The set trap is a method that catches every write to a property. Here the value -5 is refused. Inside the trap, obj is the real object, prop is the property's name, and value is the new value. throw refuses the write, obj[prop] = value stores the value, and return true reports that the write succeeded.

⚡ A get trap decides the result

Write:

const p = new Proxy({ name: 'Budi' }, {
  get(obj, prop) {
    return prop in obj ? obj[prop] : 'not found'
  }
})
Guess first: what does p.age give?

'not found', not undefined. The object has no age property, so the trap returns 'not found'. Whatever the get trap returns becomes the result of the read.

Meaning: The get(obj, prop) trap runs every time a property is read through the Proxy. prop in obj checks whether that property exists on the real object. Whatever the trap returns becomes the result of the read.

⚡ Reflect forwards it as it is

Write:

set(obj, prop, value) {
  console.log(`Writing ${prop} = ${value}`)
  return Reflect.set(obj, prop, value)
}

Meaning: This code is the set trap of a Proxy. Reflect.set(obj, prop, value) is the same as obj[prop] = value, and returns true when it succeeds. So a trap can record the write first, then forward the operation in one line.

What you will learn