javascript / expert
Snippet
Recursive Proxy for Deep Immutability
Standard Object.freeze is shallow. By using a Recursive Proxy, we can intercept access to nested objects and wrap them in their own read-only proxies dynamically, ensuring true deep immutability without upfront traversal costs.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const deepFreeze = (obj) => {return new Proxy(obj, {get(target, prop) {const value = Reflect.get(target, prop);return (value && typeof value === 'object') ? deepFreeze(value) : value;},set() {throw new Error('This object is read-only');},deleteProperty() {throw new Error('This object is read-only');}});};const config = deepFreeze({ api: { endpoint: 'v1' } });config.api.endpoint = 'v2'; // Throws Error
nextjs
Breakdown
1
get(target, prop) { ... }
Intercepts property access to check if the returned value should also be proxied.
2
deepFreeze(value) : value;
Recursively wraps nested objects in a proxy only when they are accessed (lazy evaluation).
3
set() { throw new Error(...); }
Explicitly prevents any modifications to the object properties.