Sub topic 11
Revocable Proxies
This chapter assumes you already know how to create a proxy with new Proxy(target, handler), how traps forward to the target with Reflect, and what proxy invariants are. A revocable proxy is a normal proxy with an off switch. Until you flip the switch, it behaves exactly like any other proxy. Once you flip it, every operation that would reach a trap throws a TypeError. The proxy object still exists, but it no longer leads to the target.
Why You Would Want an Off Switch
Suppose you give an object to code you do not fully control, such as a plugin, a third-party widget, or a callback that runs later. Once that code holds a reference, you cannot take the reference back. JavaScript has no operation for reaching into someone else's variables and clearing them.
A revocable proxy changes what you hand out. The other code gets the proxy, not the target. Later you can cut the link between the proxy and the target. The other code keeps its reference, but the reference becomes useless.
This idea is called a capability. Holding the reference gives you the right to use the object, and the right can be withdrawn without anyone's cooperation.
Creating a Revocable Proxy
Proxy.revocable(target, handler) takes the same two arguments as the Proxy constructor. It returns a plain object with two properties: proxy, which is the proxy itself, and revoke, which is a function that takes no arguments.
const { proxy, revoke } = Proxy.revocable({ a: 1 }, {});
console.log(proxy.a); // 1
revoke();
try {
proxy.a;
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // engine-specific, e.g. "Cannot perform 'get' on a proxy that has been revoked"
}The handler here is empty, so before revocation every operation goes to the target with default behavior. You can use any handler you like. Revocation applies whatever traps the handler defines.
Proxy.revocable is a plain function, not a constructor. Calling new Proxy.revocable(...) throws a TypeError.
What Revocation Does Internally
Every proxy has two internal slots, [[ProxyTarget]] and [[ProxyHandler]]. When an operation such as [[Get]] runs on a proxy, the engine first reads [[ProxyHandler]]. If that slot is null, the engine throws a TypeError before it looks up any trap.
Calling revoke() sets both slots to null. Revocation has three consequences:
- Every internal method fails. All thirteen internal methods (
[[Get]],[[Set]],[[HasProperty]],[[Delete]],[[OwnPropertyKeys]],[[Call]],[[Construct]], and the descriptor, prototype, and extensibility methods) start with the same null check. No operation gets through, including operations for which your handler defines no trap. - The target is untouched. Revoking the proxy does not freeze, clear, or change the target. Code that holds the target directly can keep using it.
- References are released. The proxy no longer points to the target or the handler. If nothing else references them, the garbage collector can reclaim them, even though the revoked proxy itself is still alive.
revoke is idempotent, meaning that calling it more than once is safe. After the first call, later calls do nothing. Internally, revoke holds its own reference to the proxy and drops that reference on the first call.
const { proxy, revoke } = Proxy.revocable({}, {});
revoke();
revoke(); // no error, no effectWhat Still Works After Revocation
Some operations never call a proxy's internal methods, and those keep working. Code that inspects a revoked proxy can therefore get confusing results. Some checks succeed and others throw.
| Operation on a revoked proxy | Result | Reason |
|---|---|---|
| `proxy.x`, `proxy.x = 1` | Throws `TypeError` | `[[Get]]` / `[[Set]]` |
| `'x' in proxy`, `delete proxy.x` | Throws `TypeError` | `[[HasProperty]]` / `[[Delete]]` |
| `Object.keys(proxy)`, `for...in` | Throws `TypeError` | `[[OwnPropertyKeys]]` |
| `Object.getPrototypeOf(proxy)` | Throws `TypeError` | `[[GetPrototypeOf]]` |
| `` `${proxy}` ``, `String(proxy)` | Throws `TypeError` | Reads `Symbol.toPrimitive` via `[[Get]]` |
| `Array.isArray(proxy)` | Throws `TypeError` | The spec checks for revocation explicitly |
| `typeof proxy` | Works | Decided when the proxy was created |
| `proxy === other` | Works | Identity comparison, no trap |
| Using it as a `WeakMap` key or `Set` member | Works | Identity only |
| `proxy()` on a revoked function proxy | Throws `TypeError` | `[[Call]]` |
typeof still works because whether a proxy is callable is fixed when the proxy is created. A proxy over a function keeps reporting "function" after revocation, but calling it throws.
const { proxy: fn, revoke } = Proxy.revocable(function () { return 1; }, {});
revoke();
console.log(typeof fn); // 'function'
try {
fn();
} catch (err) {
console.log(err instanceof TypeError); // true
}A Revoked Proxy in a Prototype Chain
A revoked proxy can still sit in another object's prototype chain. Lookups that stop at an own property succeed. Lookups that walk up into the revoked proxy throw.
const { proxy, revoke } = Proxy.revocable({ inherited: 'yes' }, {});
const child = Object.create(proxy);
child.own = 'mine';
console.log(child.inherited); // 'yes'
revoke();
console.log(child.own); // 'mine' (found before reaching the proxy)
try {
child.inherited;
} catch (err) {
console.log(err instanceof TypeError); // true
}Revoking a shared prototype therefore breaks every object that inherits from it, but only on lookups that miss their own properties. A failure like that shows up only for certain keys and is hard to trace back to the revocation.
Revocable Proxy Versus a Flag in the Handler
You could build an off switch yourself by keeping a boolean in the handler and checking it in each trap:
function makeSwitchable(target) {
let enabled = true;
const check = () => {
if (!enabled) throw new TypeError('access disabled');
};
const proxy = new Proxy(target, {
get(t, prop, receiver) { check(); return Reflect.get(t, prop, receiver); },
set(t, prop, value, receiver) { check(); return Reflect.set(t, prop, value, receiver); }
// ...and eleven more traps, each calling check()
});
return { proxy, disable: () => { enabled = false; } };
}The two approaches differ in the following ways:
| Concern | `Proxy.revocable` | Flag in handler |
|---|---|---|
| Coverage | All internal methods, automatically | Only the traps you remember to write |
| Memory | Releases target and handler | Proxy keeps both alive forever |
| Can be re-enabled | No, revocation is permanent | Yes, flip the flag back |
| Custom error message | No, the engine's message | Yes |
| Can allow some operations after disabling | No | Yes, such as reads but not writes |
Use Proxy.revocable when access should end permanently and completely. Use a flag when you need to switch access back on, or when you want something partial such as read-only mode. You can also combine the two: use a flag for temporary restrictions, and keep revoke for the permanent shutdown.
Pattern: Time-Limited Access
A common use is access that expires on its own.
function grantTemporary(target, ms) {
const { proxy, revoke } = Proxy.revocable(target, {});
setTimeout(revoke, ms);
return proxy;
}
const session = { user: 'ada', token: 'abc123' };
const handle = grantTemporary(session, 100);
console.log(handle.user); // 'ada'
setTimeout(() => {
try {
console.log(handle.user);
} catch (err) {
console.log('expired:', err instanceof TypeError); // expired: true
}
}, 200);The caller of grantTemporary never sees revoke, so only the timer can end access. To give a supervisor control instead, return revoke to the supervisor and give proxy to the consumer.
The Leak Problem and a Small Membrane
Revocation only cuts the link at the proxy itself. Any value the consumer read before revocation is a plain reference to the real value, and revocation does not reach it.
const config = { db: { host: 'localhost' } };
const { proxy, revoke } = Proxy.revocable(config, {});
const db = proxy.db; // the real inner object, not a proxy
revoke();
console.log(db.host); // 'localhost': still accessibleTo close this gap, wrap every object that comes out of the proxy in its own revocable proxy, and revoke them all together. This structure is called a membrane: a boundary where everything that crosses gets wrapped.
function createMembrane(root) {
const revokers = [];
const cache = new WeakMap();
function wrap(value) {
const isObject = value !== null &&
(typeof value === 'object' || typeof value === 'function');
if (!isObject) return value;
if (cache.has(value)) return cache.get(value);
const { proxy, revoke } = Proxy.revocable(value, {
get(target, prop, receiver) {
return wrap(Reflect.get(target, prop, receiver));
},
apply(target, thisArg, args) {
return wrap(Reflect.apply(target, thisArg, args));
}
});
cache.set(value, proxy);
revokers.push(revoke);
return proxy;
}
return {
proxy: wrap(root),
revokeAll() {
revokers.forEach((revoke) => revoke());
}
};
}
const config = {
db: { host: 'localhost' },
getHost() { return this.db.host; }
};
const membrane = createMembrane(config);
const db = membrane.proxy.db; // a wrapped proxy now
console.log(db.host); // 'localhost'
console.log(membrane.proxy.getHost()); // 'localhost'
membrane.revokeAll();
try {
db.host;
} catch (err) {
console.log('db revoked:', err instanceof TypeError); // db revoked: true
}The WeakMap cache makes sure each real object gets exactly one proxy. Without it, membrane.proxy.db === membrane.proxy.db would be false, and the revokers array would grow on every read.
This membrane is deliberately small. A complete membrane also unwraps arguments passed into functions, wraps values passing in both directions, and handles every trap, not only get and apply.
Common Mistakes
- Handing out
revokealong withproxy. If the consumer gets the whole result object fromProxy.revocable, it can revoke its own access or passrevokealong to others. Destructure the result and pass on onlyproxy. - Assuming revocation protects the target. Revocation only cuts off this one proxy. Any code that holds the target directly is unaffected.
- Forgetting about values already extracted. Without a membrane, anything read before revocation stays reachable.
- Expecting to undo revocation. It is permanent. Create a new proxy if access should come back.
- Logging a revoked proxy.
console.login Node and in browsers inspects proxies specially and may not throw, butString(proxy)and template literals do throw. Do not rely on stringifying a proxy you might have revoked.
Exercise
After the code below runs, which lines print and which throw? const { proxy, revoke } = Proxy.revocable([1, 2, 3], {}); const first = proxy[0]; revoke(); console.log(first); console.log(typeof proxy); console.log(Array.isArray(proxy)); console.log(proxy.length);
Show answer
console.log(first) prints 1, because the primitive was read before revocation. typeof proxy prints 'object', because typeof does not touch the proxy's internal methods. Array.isArray(proxy) throws a TypeError, because IsArray checks for a revoked proxy explicitly. The last line never runs, but proxy.length would also throw, because it calls [[Get]].
Exercise
Write a function grantReadOnly(target) that returns { proxy, revoke }. Before revocation, the proxy allows reads but makes every write fail. In strict mode, the failed writes should throw.
Show answer
Use Proxy.revocable with set, deleteProperty, and defineProperty traps that return false: function grantReadOnly(target) { return Proxy.revocable(target, { set() { return false; }, deleteProperty() { return false; }, defineProperty() { return false; } }); }. Returning false from these traps makes the operation throw a TypeError in strict mode, and makes it fail silently in sloppy mode. Reads have no trap, so they go to the target. After revoke(), every operation throws, whatever traps the handler defines.
Exercise
In the createMembrane example, why does membrane.proxy.getHost() still return 'localhost', even though getHost runs with this set to a proxy and not to the real config?
Show answer
Calling membrane.proxy.getHost() reads getHost through the get trap, which returns a wrapped function. Calling it triggers the apply trap with thisArg set to the root proxy. Reflect.apply then runs the real getHost with this as the root proxy. Inside, this.db goes through the get trap and returns the wrapped db, and .host returns the string 'localhost', which wrap passes through unchanged. Every step works because the proxies forward with Reflect before revocation.