Proxy Pattern - Controlled Access in TypeScript

Master the Proxy pattern for controlling access to objects. TypeScript examples for caching, lazy loading, access control, logging, and virtual proxies.

Structural

Detailed Explanation

Proxy Pattern

The Proxy pattern provides a surrogate or placeholder for another object to control access to it. The proxy has the same interface as the real object, making it transparent to clients.

Types of Proxies

  1. Virtual Proxy: Defers creation of expensive objects until they are actually needed (lazy loading).
  2. Protection Proxy: Controls access based on permissions or authentication.
  3. Caching Proxy: Stores results of expensive operations and returns cached values for repeated requests.
  4. Logging Proxy: Records all interactions with the real object for debugging or auditing.
  5. Remote Proxy: Represents an object in a different address space (network proxy).

JavaScript Proxy API

TypeScript has first-class proxy support via the Proxy object:

const handler: ProxyHandler<Record<string, unknown>> = {
  get(target, prop: string) {
    console.log(\`Accessing: \${prop}\`);
    return target[prop];
  },
  set(target, prop: string, value) {
    console.log(\`Setting: \${prop} = \${value}\`);
    target[prop] = value;
    return true;
  }
};

const data = new Proxy({}, handler);

Proxy vs Decorator

Both wrap an object with the same interface. The difference is intent: Proxy controls access (who can call, when it loads, whether results are cached). Decorator adds new behavior (timestamps, encryption, formatting). A caching proxy does not change what the method returns; a decorator might transform it.

Performance Considerations

While proxies add indirection overhead, caching and virtual proxies typically improve overall performance by avoiding expensive operations. The key is choosing the right proxy type for your bottleneck.

Use Case

Proxy is widely used for image lazy loading on web pages, API response caching, access control middleware that checks permissions before forwarding requests, database connection pooling, and logging/monitoring wrappers for production services.

Try It — Design Pattern Reference

Open full tool