Skip to content
jshacks.dev
Patterns

The Proxy Pattern in JavaScript, With Real Examples

The proxy pattern puts a stand-in in front of an object to control access. See lazy loading, access checks and the built-in Proxy object in JavaScript.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm and TypeScript logos.

The proxy pattern places a stand-in object in front of another object and controls access to it. The stand-in has the same interface, so callers cannot tell the difference, and it can do things the real object does not: create it lazily, check permissions, cache results, log calls or forward them across a network. JavaScript has a built-in Proxy class, introduced in ES2015, that makes the pattern unusually direct, since you can intercept property reads, writes, function calls and more. This post covers the pattern both ways, hand-written wrappers and the built-in Proxy, with lazy loading, access control, validation, change tracking and a remote-call example on Node.js 24. It also covers the performance and this pitfalls and how the pattern differs from a decorator. Every sample prints its output.

What a proxy is for

The classic catalog lists several reasons for a stand-in.

  • Virtual proxy: delay creating an expensive object until it is used.

  • Protection proxy: check whether the caller may perform an operation.

  • Remote proxy: represent an object that lives in another process or machine.

  • Caching proxy: keep results of expensive calls.

  • Logging or counting proxy: record how the object is used.

All of them share the structure: same interface, extra control in front.

A virtual proxy: lazy loading

Here is a report whose construction is expensive, and a proxy that postpones it.

lazy.mjsJavaScript
class HeavyReport {
  constructor(id) {
    console.log(`building report ${id} (expensive)`);
    this.id = id;
    this.rows = [1, 2, 3];
  }
  summary() {
    return `report ${this.id}: ${this.rows.length} rows`;
  }
}

class LazyReport {
  #id;
  #real = null;

  constructor(id) {
    this.#id = id;
  }

  summary() {
    this.#real ??= new HeavyReport(this.#id);
    return this.#real.summary();
  }
}

const report = new LazyReport(7);
console.log("proxy created");
console.log(report.summary());
console.log(report.summary());
Text
proxy created
building report 7 (expensive)
report 7: 3 rows
report 7: 3 rows

The expensive work ran once, on the first call, not when the proxy was created. Code holding the proxy can pass it around freely and only pays if it ever calls summary. This is the same trick ORMs use for lazy-loaded relations.

The built-in Proxy

new Proxy(target, handler) returns an object whose operations are routed through functions in handler, called traps. The most used traps are get, set, has, deleteProperty and apply.

builtin.mjsJavaScript
const user = { name: "Ada", role: "admin" };

const watched = new Proxy(user, {
  get(target, prop, receiver) {
    console.log(`read ${String(prop)}`);
    return Reflect.get(target, prop, receiver);
  },
  set(target, prop, value, receiver) {
    console.log(`write ${String(prop)} = ${value}`);
    return Reflect.set(target, prop, value, receiver);
  },
});

watched.name;
watched.role = "owner";
console.log(user.role);
Text
read name
write role = owner
owner

Every read and write on watched passed through the traps, and the changes reached the original user. Reflect.get and Reflect.set perform the default behavior, which keeps getters, setters and inheritance working. Forgetting to return true from a set trap, or returning a falsy value, throws a TypeError in strict mode, so return the result of Reflect.set.

A protection proxy

Access checks fit naturally into traps.

protection.mjsJavaScript
function readOnly(target, allowedWriters = []) {
  return new Proxy(target, {
    set(obj, prop) {
      throw new Error(`Cannot modify "${String(prop)}": object is read-only`);
    },
    deleteProperty(obj, prop) {
      throw new Error(`Cannot delete "${String(prop)}": object is read-only`);
    },
  });
}

const config = readOnly({ region: "eu-west-1", retries: 3 });
console.log(config.region);
try {
  config.retries = 5;
} catch (err) {
  console.log(err.message);
}
try {
  delete config.region;
} catch (err) {
  console.log(err.message);
}
Text
eu-west-1
Cannot modify "retries": object is read-only
Cannot delete "region": object is read-only

Object.freeze would also make config immutable, with a quieter failure in sloppy mode, while a proxy lets you choose the error and add rules, such as allowing writes only for some keys or only for some callers. A protection proxy is also where role checks go.

roles.mjsJavaScript
function withAuthorization(service, user) {
  return new Proxy(service, {
    get(target, prop, receiver) {
      const value = Reflect.get(target, prop, receiver);
      if (typeof value !== "function") return value;
      return (...args) => {
        if (prop === "deleteAccount" && user.role !== "admin") {
          throw new Error(`${user.name} is not allowed to ${prop}`);
        }
        return value.apply(target, args);
      };
    },
  });
}

const accounts = {
  view: (id) => `account ${id}`,
  deleteAccount: (id) => `deleted ${id}`,
};

const asMember = withAuthorization(accounts, { name: "Bob", role: "member" });
const asAdmin = withAuthorization(accounts, { name: "Ada", role: "admin" });

console.log(asMember.view(1));
try {
  asMember.deleteAccount(1);
} catch (err) {
  console.log(err.message);
}
console.log(asAdmin.deleteAccount(1));
Text
account 1
Bob is not allowed to deleteAccount
deleted 1

The service has no idea authorization exists, and the check is applied by wrapping at the composition root. Do not treat this as your only line of defense, though: enforce permissions on the server for anything that matters, and never rely on a client-side proxy for security.

A validating proxy

Intercepting set is a neat way to enforce rules on assignment.

validation.mjsJavaScript
const validator = {
  set(target, prop, value) {
    if (prop === "age" && (!Number.isInteger(value) || value < 0 || value > 150)) {
      throw new RangeError(`Invalid age: ${value}`);
    }
    return Reflect.set(target, prop, value);
  },
};

const person = new Proxy({ name: "Ada", age: 36 }, validator);
person.age = 37;
console.log(person.age);
try {
  person.age = -1;
} catch (err) {
  console.log(err.message);
}
console.log(person.age);
Text
37
Invalid age: -1
37

Failed assignments leave the old value. Vue 3's reactivity system uses the same mechanism: reactive state is wrapped in a Proxy, the get trap records which code read a property, and the set trap triggers those readers again.

A caching proxy for function calls

The apply trap intercepts calls to a function.

apply.mjsJavaScript
function memoized(fn) {
  const cache = new Map();
  return new Proxy(fn, {
    apply(target, thisArg, args) {
      const key = JSON.stringify(args);
      if (cache.has(key)) return cache.get(key);
      const result = Reflect.apply(target, thisArg, args);
      cache.set(key, result);
      return result;
    },
  });
}

let calls = 0;
const square = memoized((n) => {
  calls += 1;
  return n * n;
});

console.log(square(4), square(4), square(5));
console.log(`underlying calls: ${calls}`);
Text
16 16 25
underlying calls: 2

The proxy preserves the function's identity features such as name and length, which a plain wrapper function loses.

A remote proxy

A remote proxy makes a call that crosses a process boundary look local. This one forwards any method call to a function that stands in for the network.

remote.mjsJavaScript
function remoteService(send) {
  return new Proxy({}, {
    get(_, method) {
      return (...args) => send({ method: String(method), args });
    },
  });
}

// pretend transport that would be an HTTP or IPC call
const fakeServer = async ({ method, args }) => {
  if (method === "add") return args[0] + args[1];
  throw new Error(`Unknown method ${method}`);
};

const calculator = remoteService(fakeServer);
console.log(await calculator.add(2, 3));
try {
  await calculator.divide(1, 2);
} catch (err) {
  console.log(err.message);
}
Text
5
Unknown method divide

The get trap turns every property access into a function that sends a message. Real RPC libraries such as Comlink for worker threads use this idea. Because every call is now asynchronous, the proxy cannot fully hide that the object is remote, which is the usual limit of remote proxies.

Pitfalls

Identity. A proxy is a different object from its target, so proxy === target is false. Code that stores objects in a Set or compares references can behave differently when given the proxy.

**this and private fields.** Calling a method through a proxy sets this to the proxy, and accessing a #private field on a proxy throws a TypeError, because the proxy does not have the private slot. The fix is to bind methods to the target, as the authorization example does with value.apply(target, args).

private.mjsJavaScript
class Counter {
  #n = 0;
  inc() {
    this.#n += 1;
    return this.#n;
  }
}

const bad = new Proxy(new Counter(), {});
try {
  bad.inc();
} catch (err) {
  console.log(err.name);
}

const target = new Counter();
const good = new Proxy(target, {
  get(t, prop) {
    const v = Reflect.get(t, prop, t);
    return typeof v === "function" ? v.bind(t) : v;
  },
});
console.log(good.inc());
Text
TypeError
1

Performance. Every trapped operation costs a function call, and engines optimize proxied objects less aggressively than plain ones. For hot paths, avoid proxies, and use them for configuration, state tracking and boundaries. Measure before drawing conclusions about your own workload.

Debugging. Proxies make behavior non-obvious, since a property read can run arbitrary code. Name your traps, keep them small and document that an object is proxied.

Proxy versus decorator versus adapter

All three wrap an object. A decorator adds behavior to enhance it, a proxy controls access to the same behavior and an adapter changes the interface. In JavaScript, the same Proxy mechanism implements all three, so the intent is what separates them.

Where the advice stops

A hand-written wrapper is clearer when you only need to intercept one or two methods, and a Proxy is best when you need to intercept many or unknown property names. Do not use a proxy where a getter, a method or a plain function works. Magic hurts readers, and the traps run on every access.

Proxies for testing and debugging

A proxy is a handy tool in tests. Wrap a real dependency in a recording proxy and you can assert on how it was used without writing a hand-made spy for every method. The get trap returns a function that pushes the method name and arguments to an array and then forwards the call. After the code under test runs, the array is the list of interactions, in order. The same trick helps in debugging: wrap a configuration object in a logging proxy for an afternoon and you learn exactly which keys the application reads at startup, including the ones you did not know it used. Remove the proxy before committing, since leaving observation code in place changes performance and surprises the next reader.

Choosing a design

When deciding between a hand-written wrapper and Proxy, ask how many members you intercept. One or two named methods call for a wrapper class, since it is explicit, typed and easy to read. A whole object whose member list is unknown or large, such as a settings object or an RPC client, calls for a Proxy. If the interception rule is "everything gets the same treatment", the get trap expresses it once. If each method needs different handling, explicit methods are clearer than a growing switch inside a trap.

Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.