Revocable Proxies

Normally, a proxy can’t be unbound from its target once the proxy has been created. All of the examples to this point in this chapter have used nonrevocable proxies. But there may be situations when you want to revoke a proxy so that it can no longer be used. You’ll find it most helpful to revoke proxies when you want to provide an object through an API for security purposes and maintain the ability to cut off access to some functionality at any point in time.

You can create revocable proxies with the Proxy.revocable() method, which takes the same arguments as the Proxy constructor—a target object and the proxy handler. The return value is an object with the following properties:

  1. proxy - the proxy object that can be revoked
  2. revoke - the function to call to revoke the proxy

When the revoke() function is called, no further operations can be performed through the proxy. Any attempt to interact with the proxy object in a way that would trigger a proxy trap throws an error. For example:

  1. let target = {
  2. name: "target"
  3. };
  4. let { proxy, revoke } = Proxy.revocable(target, {});
  5. console.log(proxy.name); // "target"
  6. revoke();
  7. // throws error
  8. console.log(proxy.name);

This example creates a revocable proxy. It uses destructuring to assign the proxy and revoke variables to the properties of the same name on the object returned by the Proxy.revocable() method. After that, the proxy object can be used just like a nonrevocable proxy object, so proxy.name returns "target" because it passes through to target.name. Once the revoke() function is called, however, proxy no longer functions. Attempting to access proxy.name throws an error, as will any other operation that would trigger a trap on proxy.