Pattern 15/22 · Structural
Proxy
Put a stand-in in front of the real object: the client holds the proxy and can't tell the difference, while the proxy decides when the real object gets touched, what gets touched, and whether it gets touched at all.
01 — It starts with code that is breaking
Problem
The admin page has an orders table. Your data loader getOrder(id) pulls the order plus 4 related tables in one go, taking ~60ms. But 80% of page opens are just to see the status in a drawer. You know that. Your code doesn't: it loads everything, right away, every time, because "if you need something, call getOrder".
Problem two, N+1. A list of 200 orders, each row touches order.customer.address → 200 queries. You can fix it by remembering to write batching at every usage site. Whoever forgets one spot — and someone will — takes it down once.
Problem three, permissions. user.passwordHash sits in the object, some component happens to JSON.stringify(user) for logging, and the hash wanders off to the browser. You check permissions in 14 places, each one differently; one missing check is one data leak, and there's no single place to "tighten it once".
Problem four, reactivity. state.count++ has to trigger a re-render. For that, the object has to see every read and write. Either you make everyone write set("count", v) (the whole team will curse you), or you need something standing in between and intercepting access.
These four problems look unrelated, but they share a shape: the client needs an object, but the real object shouldn't be touched casually, or every touch needs to be recorded. And the "add an if at the top of every function that uses it" fix multiplies with the number of call sites — same disease, same cost.
02 — The idea, before touching code
Solution
A Proxy is: a stand-in with the same interface as the real object, indistinguishable to the client, sitting between the client and the real object (called the subject/proxyee) in order to decide. It holds a reference to the subject, plus a reason to exist: nothing loaded yet (virtual), what's already loaded (cache), who may see what (protection), who needs to be notified (logging/reactivity), which machine it lives on (remote).
TypeScript/JavaScript gives you the most literal version of this pattern, not a simulation: new Proxy(target, handler) — the engine calls your trap for every get, set, has, deleteProperty, ownKeys, apply, construct. Vue 3 implements reactive() with exactly Proxy: the get trap to track dependencies, the set trap to trigger effects. When you write state.a.b++, there's a proxy in between, and that is the GoF Proxy pattern, via a standard API.
The cost needs saying in full too: every access goes through a trap (slower than a plain access, and in a hot loop you measure, not guess), this inside a method called through a proxy is the proxy (sometimes what you want, sometimes a bug), private #fields and objects with internal slots (Map, Set, Date, typed arrays) break when wrapped in a proxy, and the debugger/stack traces get harder to read because the object you see isn't the object you created. Put proxies at the boundary; don't sprinkle them all over the codebase.
03 — Doing it for real, one code fragment per step
Step by step
Name the reason: four kinds of proxy, don't cram them into one file
Before writing a trap, pick one reason. Virtual proxy: defer creating/loading the subject. Caching proxy: keep results so you don't recompute/refetch. Protection proxy: decide who gets to see what. Logging/reactive proxy: record or emit a notification on every access. Remote proxy: the subject lives in another process/host (JSON-RPC, tRPC client).
A fifth reason, "to make it tidier", is Facade, not Proxy. A proxy keeps the subject's interface; if you change the interface to make it easier to use, you're doing a different pattern.
virtual : Order -> hit the DB on first field access (lazy)
caching : fn(sku)-> Map -> only call fn on a miss (memoize)
protection : user -> Set -> which fields get exposed (role)
reactive : state -> Set -> who reads what, who must rerun (signal)
remote : api -> socket -> method name + args go over the network
Facade : changes the interface to make it SIMPLER.
Adapter : changes the interface to make it FIT.
Proxy : KEEPS the interface, adds decision power in between.The SHAPE of traps in JS: new Proxy(target, handler)
handler is an object holding the traps; for any trap you don't declare, the default behavior goes straight through to the target. That's why a proxy is "transparent": 99% of operations are untouched.
Two common constraints: the set trap must return true on success (otherwise code in strict mode throws a TypeError), and a trap can't tell outright lies — engine invariants forbid get from returning something different from the target for a non-configurable property, and forbid has from returning false for an existing non-configurable property.
const target: Record<string | symbol, unknown> = { role: 'guest', name: 'Kevin' }
const p = new Proxy(target, {
get: (obj, key) => (key in obj ? obj[key] : 'missing'),
set: (obj, key, value) => {
obj[key] = value
return true // forget this: no return true -> strict mode throws
},
has: (obj, key) => key !== 'role', // 'role' in p -> false
deleteProperty: () => false, // delete p.name -> throws (strict)
})
p.role // 'guest'
'role' in p // false
delete p.name // TypeError: not allowed
p.age = 3 // target.age === 3: the target is REALLY modifiedVirtual proxy: don't touch the DB until you really need to
This is the answer to the 60ms problem. The client holds order, its code doesn't change a single line, but loadOrderFromDb only runs when someone touches a field that actually needs the data. A handler that only reads id (which you already have) won't trigger a query.
Watch the hidden part: in, Object.keys, JSON.stringify also go through traps (has, ownKeys, getOwnPropertyDescriptor). A lazy proxy that only implements get will report "missing fields" for those operations. This is where proxies most often go wrong in real life.
function lazyOrder(id: string): Order {
let real: Order | null = null
const load = () => (real ??= loadOrderFromDb(id)) // 60ms, JOIN across 4 tables
return new Proxy({} as Order, {
get: () => load() as Order, // every field: load, then return
has: (_t, key) => key in load(),
ownKeys: () => Reflect.ownKeys(load()),
getOwnPropertyDescriptor: (_t, key) => Reflect.getOwnPropertyDescriptor(load(), key),
})
}
const order = lazyOrder('ORD-01') // 0 queries, 0 ms
console.log(order.status) // 1 query, because you really need the statusid is cheap, code that reads items pays the price. The client doesn't need to know the difference.Caching proxy: intercept an expensive function, and live with invalidation
Wrapping a function is a proxy too: the apply trap catches every call. Memoizing by key inside the trap means every call site is cached without any call site changing — and no call site is allowed to "do its own caching" anymore.
Two must-haves if you don't want the cache to become a bug: don't cache failures (an error is a temporary state; cache it and you freeze the breakage), and there must be a way to invalidate — otherwise your proxy is a memory leak that answers questions.
const cache = new Map<string, Promise<Product>>()
export const getProduct = new Proxy(fetchProduct, {
apply: (fn, _self, args: [string]) => {
const hit = cache.get(args[0])
if (hit) return hit
const p: Promise<Product> = fn(args[0]).catch((e) => {
cache.delete(args[0]) // errors are temporary: must not be cached forever
throw e
})
cache.set(args[0], p)
return p
},
})
export const invalidate = (sku: string) => cache.delete(sku)Protection proxy: hide fields by role — and understand the limits
To "tighten it once" instead of checking in 14 places: list the allowed fields in a Set, and block at four traps — get, has, ownKeys, getOwnPropertyDescriptor — because JSON.stringify goes through ownKeys plus get, and the in operator goes through has. Blocking only get is blocking for show.
The limits, plainly: a proxy is not a security boundary within the same process. Any code holding a reference to the original row goes around you, and a secret that's already in the target might as well already be in the attacker's RAM. A proxy like this is legitimate as an accident guardrail (logging, serializing, rendering by mistake); to really block it, don't put the secret in the object: select columns in the query, return a projection.
const PUBLIC = new Set(['id', 'name', 'verifiedAt'])
export function asPublic(row: UserRow) {
return new Proxy(row, {
get: (o, k) => (PUBLIC.has(String(k)) ? (o as Record<string | symbol, unknown>)[k] : undefined),
has: (_o, k) => PUBLIC.has(String(k)),
ownKeys: () => [...PUBLIC],
getOwnPropertyDescriptor: (o, k) =>
PUBLIC.has(String(k)) ? Reflect.getOwnPropertyDescriptor(o, k) : undefined,
})
}
JSON.stringify(asPublic(row)) // {"id":..,"name":..,"verifiedAt":..} - no passwordHashReactive proxy: the set trap is where the truth lives
reactive, signals, $state — all the same mechanism: detect changes at the point of writing. With a proxy, no setters, no special API: state.count++ is a set trap.
Vue 3 is the canonical example and worth studying: reactive(obj) returns a proxy; the get trap tracks (records which effect is reading which field), the set/deleteProperty traps trigger (rerun the related effects). Nested objects are wrapped lazily right inside the get trap (that's how it goes deep without paying upfront), in goes through has, and Map/Set get their own handler for the reason in Step 7. Vue 2 couldn't do this because Object.defineProperty can't see keys being added/removed.
const subs = new Set<(key: string) => void>()
export function reactive<T extends object>(target: T): T {
return new Proxy(target, {
set: (obj, key, value) => {
const changed = Reflect.get(obj, key) !== value
const ok = Reflect.set(obj, key, value)
if (ok && changed) subs.forEach(fn => fn(String(key))) // 1 line: the whole app re-renders
return ok
},
deleteProperty: (obj, key) => {
const ok = Reflect.deleteProperty(obj, key)
if (ok) subs.forEach(fn => fn(String(key)))
return ok
},
})
}
export const onChange = (fn: (key: string) => void) => (subs.add(fn), () => subs.delete(fn))Three technical traps: this, private fields, internal slots
Trap 1 — this. Call p.method() and inside the method, this is the proxy (what reactivity needs, but also a source of bugs). Detach the method from the object (const fn = p.method; fn()) and this becomes undefined just like with a regular object, so a method reading this.x blows up.
Trap 2 — private #field. A private field isn't a property; it's an internal slot, so the trap can't see it and the brand check fails: reading #pin through a proxy throws a TypeError (the message varies by engine). Trap 3 — objects with internal slots is even nastier: Map, Set, Date, typed arrays need the object's own internal slots, so wrapping them in a proxy breaks their methods — new Proxy(new Map(), {}).set(...) throws "incompatible receiver". Arrays survive, because an array is just an object + length.
class Account {
#pin = '1234'
name = 'bank'
whoami() { return this.name }
readPin() { return this.#pin }
}
const p = new Proxy(new Account(), {})
p.whoami() // 'bank' -> this IS the proxy, still correct
const fn = p.whoami // detached method: loses the this binding
// fn() // TypeError: can't read this.name
// p.readPin() // TypeError: private fields don't pass through the trap
const m = new Proxy(new Map<string, number>(), {})
// m.set('a', 1) // TypeError: not a real Map (missing internal slot)
const d = new Proxy(new Date(), {})
// d.getTime() // TypeError, same thing
const a = new Proxy([1, 2, 3], {})
a.push(4) // OK: arrays don't need internal slots
console.log(a.length) // 4Last step: consider not using Proxy
A proxy is a boundary tool: a thin layer where data enters/leaves, where you control all the traffic. Sprinkling reactive()/proxy wrappers across 200 modules is the fastest way to fill your profiler with traps and make your debugger useless.
Most needs have a cheaper version: need a computed field → a getter. Need to cache a function → a memoizing closure, no apply trap needed. Need to kill N+1 → DataLoader/a batch loader in the repository layer. Need "don't modify the config" → Object.freeze + a readonly type. Need "don't import things randomly" → a lint rule at the module level. Proxy wins when you need to intercept a whole family of accesses without changing call sites — otherwise, don't.
what you need -> cheaper option Proxy is worth it when
computed field -> getter no access needs intercepting
cache 1 function -> memo closure EVERY call site must hit the cache
N+1 queries -> DataLoader access is scattered, hard to control
config must not change -> Object.freeze you just need it not to be modified
test/audit access -> Proxy (trap) the one thing only a trap can do04 — Who talks to whom
Structure
- Subject (interface)The shape the client expects. The proxy **must** match it exactly — that's the condition for the client not being able to tell them apart.
- ProxyThe stand-in: holds a reference to the subject + a **reason** (lazy, cache, role, tracking). Only after a trap fires does the call continue to the subject.
- Proxyee / RealSubjectThe real object: a DB row with 4 JOINed tables, an expensive function, a remote resource. Slow, expensive, or sensitive.
- ClientReads/writes through the proxy as if it were a regular object. Doesn't know (and doesn't need to know) there's anything in between.
- Observer(reactive version) Subscribes to notifications when the `set`/`deleteProperty` trap catches a change.
Client Proxy (handler) Proxyee (real)
------ ----------------- --------------
order.status ──get──► │ get: load if not loaded │
order.items ──get──► │ set: write + notify subs │ 60ms,
'items' in ──has──► │ has/ownKeys: hide secrets │ 4 JOINs
JSON.stringify ──────► │ apply: memoize by key │ sensitive
└──────────┬─────────────────┘
│ continues only if the trap allows
▼
trap = the ONLY interception point, in one place,
the client doesn't change a single line05 — Edit freely, run it right here
Try it: three traps, three reasons, in 40 lines
const dirty = new Set<string>()
// 1) Reactive proxy: the set trap detects changes (a stripped-down Vue 3 reactive())
const state = new Proxy({ cart: 0, coupon: '' } as Record<string | symbol, unknown>, {
set: (obj, key, value) => {
const changed = obj[key] !== value
obj[key] = value
if (changed) dirty.add(String(key))
return true
},
})
state.cart = 1
state.cart = 1 // unchanged -> not dirty, key isn't added again
state.coupon = 'SALE50'
// 2) Caching proxy: intercept an expensive function, memoize by argument
let dbCalls = 0
const priceOf = (sku: string) => {
dbCalls++
return sku.length * 10
}
const cache = new Map<string, number>()
const price = new Proxy(priceOf, {
apply: (fn, _self, args: unknown[]) => {
const key = String(args[0])
if (!cache.has(key)) cache.set(key, fn(key))
return cache.get(key)
},
})
// 3) Access-control proxy: which fields a guest may see, and nothing more
const row = { sku: 'A1', cost: 40, margin: 0.6 }
const allowed = new Set(['sku', 'cost'])
const guestView = new Proxy(row, {
get: (o, k) => (allowed.has(String(k)) ? (o as Record<string | symbol, unknown>)[k] : undefined),
has: (_o, k) => allowed.has(String(k)),
})
console.log('dirty: ' + [...dirty].join(','))
console.log('price x3 = ' + [1, 2, 3].map(() => price('A1')).join('/') + ' dbCalls=' + dbCalls)
console.log('guest sku=' + guestView.sku + ' margin=' + guestView.margin + ' hasMargin=' + ('margin' in guestView))dirty: cart,coupon price x3 = 20/20/20 dbCalls=1 guest sku=A1 margin=undefined hasMargin=false
The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.
06 — Honest about the cost
When to use it, when not to
Use it when
- Defer a large cost until right before it's needed, when the calling interface must not change (lazy relations, per-field hydration, lazy rows).
- You need to catch every access at one point: caching, audit logs, telemetry, permissions — without editing dozens of call sites.
- You need state where real mutation (
obj.x = 1) is still detectable: reactive stores, signals, copy-on-write drafts. - You need a reduced-privilege view of an object (role, tenant, preview mode) instead of hand-projecting in every route.
- The subject lives elsewhere (another process, the network) but the client still wants to call it like a local object — RPC clients, tRPC-style stubs.
- You need to verify access in tests/dev: block writes to config, detect who reads a deprecated field.
Don't use it when
- A proxy is not a sandbox. Code in the same process holding a reference to the target goes right around you; a secret that's in the target is already in RAM. Real blocking = projection in the query, not a trap.
- Objects with internal slots really do break:
Map,Set,Date, typed arrays,WeakMap, Promise (the native instance) — their methods require their own slots, and wrapping them in a proxy gives aTypeError. Arrays survive; don't generalize from arrays. thisis the proxy, so everythis.xinside a method goes through a trap again (fast or slow depending on the loop), and a method detached from its object loses its binding and blows up. Proxy + a class with many methods is where bugs hide the longest.- Private
#fields are invisible to traps. Your trap logic can't see them, and accessing them through a proxy throws a TypeError. If your class lives on private state, wrapping it in a proxy isn't a viable design. - Writing only a
gettrap is a latent bug:in,Object.keys,JSON.stringify,structuredClone, and spread all go throughhas/ownKeys/getOwnPropertyDescriptor. Miss one trap and behavior drifts silently. - Real cost: one trap per access, and proxies inside proxies (deep reactivity) multiply the trap count. In a hot loop, a
Mapis usually still faster than a proxy-wrapped object — measure, don't trust blogs. - Over-engineering. Sprinkle proxy wrappers across the codebase and announce "state is reactive now" — the profiler fills up with traps, the debugger goes blind, and nobody can explain why reading one field runs three functions. If a getter solves it, don't multiply proxies.
- Don't confuse it with an HTTP proxy in config: Nuxt's
routeRules.proxyor Vite'sserver.proxyis a reverse proxy at the network layer — same "stand in between" spirit, completely different from this object pattern.
07 — You have met it already, just not by name
In real code
Vue 3 reactive() / ref()
reactive(obj) returns new Proxy(obj, handler) with get (track), set, deleteProperty, has, ownKeys traps; nested objects are wrapped lazily in the get trap; Map/Set go through a separate collection handler because of internal slots. Vue 2 couldn't do this because Object.defineProperty can't see keys being added/removed — which is exactly why the Vue.set API existed.
Immer produce()
Immer builds a draft with a Proxy: the get trap returns nested drafts, the set trap writes to a copy (copy-on-write), and then produce returns a new immutable object. You mutate normally, the library eavesdrops through traps to compute the diff — the Proxy pattern sitting right under the API.
DataLoader
A stand-in object in front of a load function, memoizing by key within a single request and coalescing loads into one batch. It isn't new Proxy, but in shape it's a caching + batching proxy: the call site calls loader.load(id) and knows nothing about what's in between.
Lazy relations in ORMs
TypeORM lets you declare relations as Promise<Entity>, loaded when you touch the property — a virtual proxy via a getter, no new Proxy needed. Same reason to exist, different mechanism: when the set of fields is small and fixed, a getter is simpler.
Node's require() cache
On every require, the runtime checks Module._cache first and only touches the filesystem on a miss. In essence that's a caching proxy hiding an expensive subsystem, and it teaches the invalidation lesson too: the module cache lives long, and you pay for it during hot reload.
08 — Try it yourself
Exercise
Write `readonlyGuard(config, "config")` that returns a proxy where every attempted `set`, `deleteProperty`, `defineProperty` throws an Error stating **which key and which operation**. Attach it to your app config in dev. Then answer two questions: why does `config.db.host = "x"` still get through, and why is this not a security mechanism.
Hints, open them one at a time:
- All three traps must throw the same kind of error — write a
deny(op, key)helper that returnsneverand share it. - To "block", the
settrap throws an Error, rather than just returningfalse(returningfalseonly throws in strict mode and loses the message). - The "deep" version has to keep wrapping in the
gettrap: every time it returns an object, wrap it — that's exactly how Vue 3 reactive handles nested objects.
All three traps call the same deny(), so error messages are consistent and you don't repeat code. The deep-wrap version: in the get trap, if the value is an object, return readonlyGuard(value) (don't forget to memoize by the original object so each object gets only one proxy — this is Flyweight meeting Proxy). As for the security question: this guard stops accidents, not people acting on purpose — they still have the original object in scope, and a proxy has no effect on code that doesn't go through it.
function readonlyGuard<T extends object>(obj: T, path: string): T {
const deny = (op: string, key: string | symbol): never => {
throw new Error(path + ' is readonly: ' + op + ' "' + String(key) + '"')
}
return new Proxy(obj, {
set: (_t, key) => deny('set', key),
deleteProperty: (_t, key) => deny('delete', key),
defineProperty: (_t, key) => deny('define', key),
// deep: nested objects must be guarded too
get: (o, key) => {
const value = Reflect.get(o, key)
return value && typeof value === 'object' ? readonlyGuard(value, path + '.' + String(key)) : value
},
})
}
const config = readonlyGuard({ db: { host: 'localhost' }, port: 3000 }, 'config')
config.port = 8080 // Error: config is readonly: set "port"
config.db.host = 'evil' // Error: config.db is readonly: set "host"09 — Read them in pairs to see the essence
Related patterns
- FacadeBoth "stand in front of" something else. Facade **changes** the interface to make a subsystem easier to use; Proxy **keeps** the interface to control access. If your client has to learn a new API, it's no longer a Proxy.
- DecoratorDecorator adds behavior by wrapping **statically and deliberately** — whoever writes that code knows the wrapper is there. Proxy adds behavior **transparently** — the client can't tell. Decorator is cheaper and easier to debug; Proxy only gets its turn when you need to intercept all access.
- AdapterAdapter exists because the interfaces **don't match**; Proxy exists because **access** needs to be controlled, and it deliberately leaves the interface alone.
- CommandA common pairing in remote proxies: the proxy translates each method call into a Command object, sends it off, the other side runs it and returns the result. An RPC client is essentially a proxy that generates commands.