Sub topic 12
Practical Patterns: Validation, Logging, Defaults, and Hidden Properties
This chapter builds four reusable wrappers on top of the trap mechanics from earlier chapters. It assumes you already know how to write get, set, has, deleteProperty, ownKeys, and defineProperty traps, how to forward each one with the matching Reflect method, and why the receiver argument matters. Each pattern below comes with the details that make it hold up in practice: which traps it needs, which operations get around a naive version, and which invariants restrict it.
Validation: Guarding Every Write
A set trap that checks values is the usual first validation proxy. It has a gap, though. Object.defineProperty(proxy, 'price', { value: -1 }) never calls set. It calls the defineProperty trap. If you validate only in set, anyone can get around the check with one function call.
There is a simpler design. Ordinary property assignment ends in a [[DefineOwnProperty]] call on the receiver. When the receiver is the proxy, that call reaches the proxy's defineProperty trap. So a single defineProperty trap covers plain assignment and explicit Object.defineProperty calls.
function withSchema(target, schema) {
const check = (prop, value) => {
// Object.hasOwn avoids matching inherited keys such as "toString"
if (!Object.hasOwn(schema, prop)) return;
const rule = schema[prop];
if (!rule.test(value)) {
throw new TypeError(`Invalid ${String(prop)}: ${rule.message}`);
}
};
return new Proxy(target, {
defineProperty(target, prop, descriptor) {
if ('value' in descriptor) {
check(prop, descriptor.value);
} else if (Object.hasOwn(schema, prop) && ('get' in descriptor || 'set' in descriptor)) {
throw new TypeError(`${String(prop)} cannot be an accessor`);
}
return Reflect.defineProperty(target, prop, descriptor);
}
});
}
const product = withSchema({}, {
price: { test: (v) => typeof v === 'number' && v >= 0, message: 'non-negative number' },
name: { test: (v) => typeof v === 'string' && v.length > 0, message: 'non-empty string' }
});
product.price = 10; // ok
product.name = 'Lamp'; // ok
try { product.price = -5; } catch (e) { console.log(e.message); }
// Invalid price: non-negative number
try { Object.defineProperty(product, 'price', { value: -1 }); } catch (e) { console.log(e.message); }
// Invalid price: non-negative number
console.log(product.price); // 10Some details in this code matter:
- The check uses
Object.hasOwn(schema, prop)rather thanschema[prop]. A plain object inheritstoString,constructor, and other keys fromObject.prototype. Withschema[prop], writingproduct.toString = ...would look up a "rule" that is really a function with notestmethod, and the trap would crash. - The trap rejects accessor descriptors for schema keys. Without that rule, a caller could define a getter that returns any value it likes.
- The trap throws instead of returning
false. Afalseresult throws a genericTypeErrorin strict mode and fails silently in sloppy mode. Throwing your own error gives the same behavior in both modes and a useful message.
Logging: A Handler Built from Reflect
A tracing proxy should log every operation, not only reads and writes. The 13 trap names match the 13 methods on Reflect exactly. That lets you build the handler in a loop instead of writing every trap by hand:
const KEYED = new Set([
'get', 'set', 'has', 'deleteProperty', 'defineProperty', 'getOwnPropertyDescriptor'
]);
function traced(target, log = console.log) {
const handler = {};
for (const trap of Object.getOwnPropertyNames(Reflect)) {
handler[trap] = (...args) => {
// args[0] is the target; for keyed traps args[1] is the property key
log(KEYED.has(trap) ? `${trap} ${String(args[1])}` : trap);
return Reflect[trap](...args);
};
}
return new Proxy(target, handler);
}
const obj = traced({ a: 1 });
obj.a; // get a
obj.b = 2; // set b / getOwnPropertyDescriptor b / defineProperty b
'a' in obj; // has a
Object.keys(obj); // ownKeys / getOwnPropertyDescriptor a / getOwnPropertyDescriptor bThe output shows how built-in operations break down into internal methods. One assignment fires three traps. Reflect.set walks the target's prototype chain, finds no setter, and then asks the receiver (the proxy) for its own descriptor before it defines the property on the receiver. Object.keys asks for the key list and then reads each key's descriptor to check whether it is enumerable.
That breakdown explains the validation design above. It also gives you a way to find out which traps a library depends on: wrap its input in traced and read the log.
Defaults: Values for Missing Properties
A get trap can return a fallback value for keys the target does not have. A counter object makes a clear example:
function withDefault(target, fallback) {
return new Proxy(target, {
get(target, prop, receiver) {
if (typeof prop === 'symbol' || Reflect.has(target, prop)) {
return Reflect.get(target, prop, receiver);
}
return fallback;
}
});
}
const counts = withDefault({}, 0);
for (const word of 'the cat and the hat'.split(' ')) {
counts[word] += 1;
}
console.log(counts.the, counts.cat, counts.dog); // 2 1 0
console.log('dog' in counts); // false
console.log(`${counts}`); // [object Object]Two decisions keep this proxy safe.
First, the existence test uses Reflect.has, not Reflect.get(...) === undefined. A key the caller explicitly set to undefined keeps its value, and inherited members such as toString still resolve normally.
Second, symbol keys always pass through. The engine reads well-known symbols for its own protocols. If the proxy returned 0 for Symbol.toPrimitive, ` ${counts} would throw because 0 is not callable. If it returned 0 for Symbol.iterator, [...counts]` would throw "not iterable".
String keys have the same problem. If the fallback is a function, or a proxy that creates nested objects on demand, then await proxy and Promise.resolve(proxy) read then, find something callable, and treat your object as a promise. Exclude 'then' explicitly in that kind of design.
Notice that in still reports false for dog. The proxy supplies values but does not claim the keys exist. Keep it that way unless you also update has, ownKeys, and getOwnPropertyDescriptor. If you change only some of these traps, the object gives different answers depending on which operation asks.
Hidden Properties: Every Path, Not Just Two
Hiding underscore-prefixed keys from in and Object.keys takes two traps. A thorough version has to close every other path that could reveal the key or change it:
'use strict';
const isHidden = (key) => typeof key === 'string' && key.startsWith('_');
function hidePrivate(target) {
return new Proxy(target, {
get: (t, p, r) => (isHidden(p) ? undefined : Reflect.get(t, p, r)),
set: (t, p, v, r) => (isHidden(p) ? false : Reflect.set(t, p, v, r)),
has: (t, p) => (isHidden(p) ? false : Reflect.has(t, p)),
deleteProperty: (t, p) => (isHidden(p) ? false : Reflect.deleteProperty(t, p)),
defineProperty: (t, p, d) => (isHidden(p) ? false : Reflect.defineProperty(t, p, d)),
getOwnPropertyDescriptor: (t, p) =>
(isHidden(p) ? undefined : Reflect.getOwnPropertyDescriptor(t, p)),
ownKeys: (t) => Reflect.ownKeys(t).filter((k) => !isHidden(k))
});
}
const record = hidePrivate({
_secret: 42,
visible: 2,
reveal() { return this._secret; }
});
console.log(record._secret); // undefined
console.log(Object.getOwnPropertyDescriptor(record, '_secret')); // undefined
console.log(Object.keys(record)); // ['visible', 'reveal']
console.log(JSON.stringify(record)); // {"visible":2}
try { record._secret = 0; } catch (e) { console.log(e instanceof TypeError); } // true
console.log(record.reveal()); // undefinedEach trap closes one path. Without getOwnPropertyDescriptor, Object.getOwnPropertyDescriptor(record, '_secret') would return the value. Without defineProperty, a caller could overwrite the hidden key with Object.defineProperty.
The last line shows the main cost of this design. record.reveal() calls the method with this set to the proxy, so this._secret goes through the get trap and comes back undefined. The object's own methods can no longer see its hidden data. You can fix this by binding functions to the target in get. Binding returns a new function on every read, though, so record.reveal === record.reveal becomes false. The limitations chapter discusses that identity trade-off in more detail.
The invariants also restrict this pattern. Here is what happens with a frozen target:
const sealedRecord = hidePrivate(Object.freeze({ _k: 1, v: 2 }));
try { Object.keys(sealedRecord); } catch (e) { console.log(e instanceof TypeError); } // trueownKeys must report every non-configurable own key, so the filter breaks the rule and the engine throws. has and getOwnPropertyDescriptor have the same restriction. A proxy can hide only configurable properties on an extensible target.
Composing Wrappers
Proxies can wrap other proxies, so you can combine patterns: traced(withSchema({}, schema)) logs every operation and still validates. Combining works only because every layer forwards with the correct receiver. The outer proxy's Reflect.set passes the outer proxy as the receiver. The descriptor lookup and the defineProperty call therefore start at the outer layer and then flow inward to the validator.
Order matters. The outermost layer sees operations first, so put logging outside validation if you want to log rejected writes too. Each layer also adds overhead to every operation, and the overhead adds up when you stack several.
| Pattern | Traps needed | Main gotcha |
|---|---|---|
| Validation | `defineProperty` (plus `set` for coercion) | `set`-only checks miss `Object.defineProperty` |
| Logging | All 13, generated from `Reflect` | Inspecting the receiver inside a trap runs the traps again |
| Defaults | `get` | Well-known symbols and `then` must pass through |
| Hidden properties | `get`, `set`, `has`, `deleteProperty`, `defineProperty`, `getOwnPropertyDescriptor`, `ownKeys` | Methods lose access via `this`; non-configurable keys cannot be hidden |
Use a proxy when the keys are dynamic or unknown ahead of time. If the set of properties is fixed, class accessors or Object.defineProperty give you the same checks with simpler code and better performance.
Exercise
A teammate validates writes with only a set trap that rejects negative prices. List two ways a caller can still store a negative price through the proxy, and the one-trap change that closes both.
Show answer
Calling Object.defineProperty(proxy, 'price', { value: -1 }) skips the set trap entirely. Reflect.defineProperty(proxy, 'price', { value: -1 }) also skips it. Moving the check into a defineProperty trap closes both paths, and it still covers plain assignment, because ordinary [[Set]] ends in a [[DefineOwnProperty]] call on the proxy as receiver.
Exercise
You change withDefault so it returns the fallback for symbol keys too, with a fallback of 0. What happens with ${counts} and with [...counts], and why?
Show answer
Both throw a TypeError. The template literal reads Symbol.toPrimitive and gets 0, which is not callable. Spreading reads Symbol.iterator and gets 0, which is not callable either, so the object is reported as not iterable. Well-known symbols must be forwarded to the target.
Exercise
The traced proxy logs "getOwnPropertyDescriptor b" and "defineProperty b" for obj.b = 2, but only "set a" for a later obj.a = 5? Is that correct?
Show answer
No. Both assignments go through Reflect.set with the proxy as receiver, so both log set, getOwnPropertyDescriptor, and defineProperty. For an existing property, ordinary [[Set]] still reads the receiver's own descriptor and then redefines the value on the receiver with a { value } descriptor.