Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Read-only view of an object with Proxy in JavaScript

59 A read-only view over a mutable object

hard

Hand a caller a view of your configuration that they cannot write to, delete from or redefine — while you keep writing to the original. Make it deep, so a nested object read through the view is read-only too. Then find the two things this is not: a freeze, and a stable identity.

Stuck? Three hints, smallest first
  1. 1. Three traps refuse by returning false: set, deleteProperty and defineProperty.
  2. 2. For depth, the get trap has to wrap any object it is about to hand back.
  3. 3. Wrapping on every read means a fresh proxy every time. Compare two reads of the same key with ===.

The answer

const readOnly = (target) => new Proxy(target, {
  get(t, key, receiver) {
    const value = Reflect.get(t, key, receiver);
    return value !== null && typeof value === 'object' ? readOnly(value) : value;
  },
  set: () => false,
  deleteProperty: () => false,
  defineProperty: () => false,
  setPrototypeOf: () => false,
});

const attemptName = (fn) => { try { fn(); return 'no error'; } catch (err) { return err.name; } };

const settings = {
  till: 'Balogun 3',
  limits: { perOrder: 500000, daily: 2000000 },
};
const view = readOnly(settings);

const reads = [view.till, view.limits.perOrder];
const writeAttempt = attemptName(() => { view.till = 'Ikeja 1'; });
const deleteAttempt = attemptName(() => { delete view.till; });
const defineAttempt = attemptName(() => Object.defineProperty(view, 'till', { value: 'Ikeja 1' }));
const reflectSays = [Reflect.set(view, 'till', 'Ikeja 1'), Reflect.deleteProperty(view, 'till')];
const untouched = settings.till;

const nestedWrite = attemptName(() => { view.limits.daily = 0; });
const nestedUntouched = settings.limits.daily;

settings.limits.daily = 3000000;                 // the owner still writes to the original
const viewSeesIt = view.limits.daily;
const looksFrozen = [Object.isFrozen(view), Object.isFrozen(settings)];
const sameTwice = view.limits === view.limits;

console.log('reads      :', reads);
console.log('refusals   :', [writeAttempt, deleteAttempt, defineAttempt, nestedWrite]);
console.log('view sees  :', viewSeesIt, '| identity stable:', sameTwice);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('reading through the view works normally', reads, ['Balogun 3', 500000]);
test('every kind of write throws a TypeError in strict mode', [writeAttempt, deleteAttempt, defineAttempt], ['TypeError', 'TypeError', 'TypeError']);
test('Reflect reports the same refusals as false instead of throwing', reflectSays, [false, false]);
test('and the original is untouched by any of it', untouched, 'Balogun 3');
test('a nested object read through the view is read-only too', [nestedWrite, nestedUntouched], ['TypeError', 2000000]);
test('but the owner still writes to the original, and the view shows it', viewSeesIt, 3000000);
test('so this is not a freeze: neither object is frozen', looksFrozen, [false, false]);
test('and wrapping on every read costs identity: two reads are two proxies', sameTwice, false);

A read-only view and Object.freeze solve different problems. Freezing makes the object immutable for everyone, including you. A view removes one reference's ability to write while the holder of the original carries on — which is what you want when handing configuration to a plugin, or a cache's contents to a caller who must not corrupt it. The sixth and seventh assertions are the difference stated plainly: the daily limit changed to 3,000,000 through the original and the view reported it, and Object.isFrozen is false on both.

Depth costs something, and the last assertion is the bill. Because get wraps each object as it is handed out, two reads of view.limits produce two different proxies, so === fails, a Map keyed on it gets two entries, and a React-style identity check sees a change on every render. Caching the wrappers in a WeakMap keyed by target fixes it and is the version worth shipping.

setPrototypeOf is in the handler for the same reason as the other three: without it a caller can replace the prototype and shadow behaviour without ever writing an own property. What still leaks through: a method reached via the view runs with the view as this, so a mutating method throws rather than silently failing — better, but it is a runtime error in someone else's code, so a view is a safety net, not an API.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.