Using Reflect and Proxy Together in JavaScript

Master combining JavaScript Reflect and Proxy for robust meta-programming. Covers proper trap forwarding with Reflect, invariant-safe handlers, transparent wrappers, observable objects, middleware chains, sandboxed execution, and production-ready patterns.

JavaScriptadvanced
17 min read

Reflect and Proxy are designed as complementary APIs. Proxy intercepts operations, and Reflect performs the default behavior for those operations. Using them together creates robust, invariant-safe meta-programming patterns.

For the Proxy API details, see Advanced JavaScript Proxies Complete Guide. For Reflect fundamentals, see JavaScript Reflect API Advanced Architecture.

The Forwarding Pattern

javascriptjavascript
// RULE: Every Proxy trap should use the corresponding Reflect method
// for default behavior. This ensures correct semantics.
 
// BAD: Direct object access in trap handlers
const badHandler = {
  get(target, property, receiver) {
    // Problems:
    // 1. Ignores receiver (breaks inherited getters)
    // 2. Doesn't handle Symbol keys correctly
    // 3. Doesn't respect property descriptors
    return target[property];
  },
 
  set(target, property, value, receiver) {
    // Problems:
    // 1. Returns undefined instead of boolean
    // 2. Ignores receiver (breaks inherited setters)
    // 3. Doesn't trigger defineProperty correctly
    target[property] = value;
    return true;
  }
};
 
// GOOD: Reflect forwarding in trap handlers
const goodHandler = {
  get(target, property, receiver) {
    // Correctly handles:
    // - receiver for getter 'this' binding
    // - Symbol properties
    // - Non-configurable property invariants
    return Reflect.get(target, property, receiver);
  },
 
  set(target, property, value, receiver) {
    // Correctly handles:
    // - receiver for setter 'this' binding
    // - Returns proper boolean
    // - Validates against target descriptors
    return Reflect.set(target, property, value, receiver);
  },
 
  has(target, property) {
    return Reflect.has(target, property);
  },
 
  deleteProperty(target, property) {
    return Reflect.deleteProperty(target, property);
  },
 
  ownKeys(target) {
    return Reflect.ownKeys(target);
  },
 
  getOwnPropertyDescriptor(target, property) {
    return Reflect.getOwnPropertyDescriptor(target, property);
  },
 
  defineProperty(target, property, descriptor) {
    return Reflect.defineProperty(target, property, descriptor);
  },
 
  getPrototypeOf(target) {
    return Reflect.getPrototypeOf(target);
  },
 
  setPrototypeOf(target, prototype) {
    return Reflect.setPrototypeOf(target, prototype);
  },
 
  isExtensible(target) {
    return Reflect.isExtensible(target);
  },
 
  preventExtensions(target) {
    return Reflect.preventExtensions(target);
  }
};
 
// This is a transparent proxy: it behaves identically to the target
// Now add your custom logic ON TOP of the Reflect calls

Observable Object Pattern

javascriptjavascript
// Combine Proxy (interception) + Reflect (forwarding) for observation
 
function createObservable(target) {
  const listeners = new Map();
 
  const proxy = new Proxy(target, {
    get(target, property, receiver) {
      const value = Reflect.get(target, property, receiver);
 
      // Emit 'get' events
      emit("get", { property, value });
 
      return value;
    },
 
    set(target, property, value, receiver) {
      const oldValue = Reflect.get(target, property, receiver);
      const result = Reflect.set(target, property, value, receiver);
 
      if (result && oldValue !== value) {
        emit("change", { property, oldValue, newValue: value });
      }
 
      return result;
    },
 
    deleteProperty(target, property) {
      const oldValue = target[property];
      const result = Reflect.deleteProperty(target, property);
 
      if (result) {
        emit("delete", { property, oldValue });
      }
 
      return result;
    },
 
    defineProperty(target, property, descriptor) {
      const result = Reflect.defineProperty(target, property, descriptor);
 
      if (result) {
        emit("define", { property, descriptor });
      }
 
      return result;
    }
  });
 
  function emit(event, data) {
    const callbacks = listeners.get(event);
    if (callbacks) {
      for (const cb of callbacks) {
        cb(data);
      }
    }
  }
 
  proxy[Symbol.for("observe")] = function (event, callback) {
    if (!listeners.has(event)) {
      listeners.set(event, new Set());
    }
    listeners.get(event).add(callback);
 
    // Return unsubscribe function
    return () => listeners.get(event).delete(callback);
  };
 
  return proxy;
}
 
// USAGE
const state = createObservable({ count: 0, name: "Alice" });
 
const unsubChange = state[Symbol.for("observe")]("change", (data) => {
  console.log(`Changed: ${data.property} = ${data.newValue} (was ${data.oldValue})`);
});
 
state.count = 1;   // Changed: count = 1 (was 0)
state.name = "Bob"; // Changed: name = Bob (was Alice)
 
unsubChange();      // Stop observing
state.count = 2;    // No output

Middleware Chain Pattern

javascriptjavascript
// Build a middleware pipeline using Proxy + Reflect
 
function createMiddlewareProxy(target) {
  const middleware = {
    get: [],
    set: [],
    deleteProperty: [],
    has: []
  };
 
  const proxy = new Proxy(target, {
    get(target, property, receiver) {
      let value = Reflect.get(target, property, receiver);
 
      // Run get middleware pipeline
      for (const mw of middleware.get) {
        const result = mw({ target, property, value, receiver });
        if (result !== undefined) value = result;
      }
 
      return value;
    },
 
    set(target, property, value, receiver) {
      let processedValue = value;
 
      // Run set middleware pipeline
      for (const mw of middleware.set) {
        const result = mw({
          target,
          property,
          value: processedValue,
          receiver
        });
 
        if (result === false) return false; // Block the set
        if (result !== undefined && result !== true) {
          processedValue = result; // Transform the value
        }
      }
 
      return Reflect.set(target, property, processedValue, receiver);
    },
 
    deleteProperty(target, property) {
      for (const mw of middleware.deleteProperty) {
        if (mw({ target, property }) === false) return false;
      }
      return Reflect.deleteProperty(target, property);
    },
 
    has(target, property) {
      let result = Reflect.has(target, property);
      for (const mw of middleware.has) {
        const mwResult = mw({ target, property, result });
        if (typeof mwResult === "boolean") result = mwResult;
      }
      return result;
    }
  });
 
  // API to add middleware
  proxy[Symbol.for("use")] = function (trap, handler) {
    if (middleware[trap]) {
      middleware[trap].push(handler);
    }
    return proxy;
  };
 
  return proxy;
}
 
// USAGE: Build a validated, logged, transformed data object
const data = createMiddlewareProxy({});
 
// Middleware 1: Logging
data[Symbol.for("use")]("set", ({ property, value }) => {
  console.log(`[SET] ${property} = ${JSON.stringify(value)}`);
});
 
// Middleware 2: String trimming
data[Symbol.for("use")]("set", ({ property, value }) => {
  if (typeof value === "string") return value.trim();
});
 
// Middleware 3: Validation
data[Symbol.for("use")]("set", ({ property, value }) => {
  if (property === "age" && (typeof value !== "number" || value < 0)) {
    console.error(`Invalid age: ${value}`);
    return false; // Block the set
  }
});
 
data.name = "  Alice  "; // [SET] name = "  Alice  " -> stored as "Alice"
data.age = 30;           // [SET] age = 30
data.age = -5;           // [SET] age = -5 -> Invalid age: -5 (blocked)
 
console.log(data.name);  // "Alice" (trimmed)
console.log(data.age);   // 30 (invalid set was blocked)

Sandboxed Execution

javascriptjavascript
// Use Proxy + Reflect to create controlled execution environments
 
function createSandbox(allowedGlobals) {
  const sandbox = Object.create(null);
 
  // Whitelist allowed globals
  for (const name of allowedGlobals) {
    if (name in globalThis) {
      sandbox[name] = globalThis[name];
    }
  }
 
  return new Proxy(sandbox, {
    get(target, property, receiver) {
      if (Reflect.has(target, property)) {
        return Reflect.get(target, property, receiver);
      }
 
      // Block access to non-whitelisted globals
      throw new ReferenceError(
        `${String(property)} is not available in sandbox`
      );
    },
 
    set(target, property, value, receiver) {
      // Allow setting user-defined variables
      return Reflect.set(target, property, value, receiver);
    },
 
    has(target, property) {
      // 'with' statement uses 'has' to check scope
      return true; // Trap all variable lookups
    },
 
    deleteProperty(target, property) {
      return Reflect.deleteProperty(target, property);
    }
  });
}
 
// Run code with limited access
function runInSandbox(code, allowedGlobals = ["Math", "JSON", "parseInt", "parseFloat"]) {
  const sandbox = createSandbox(allowedGlobals);
 
  // Create a function with the sandbox as its scope
  const wrappedCode = `with(sandbox) { return (function() { "use strict"; ${code} })(); }`;
 
  try {
    const fn = new Function("sandbox", wrappedCode);
    return fn(sandbox);
  } catch (error) {
    return { error: error.message };
  }
}
 
// Safe execution
console.log(runInSandbox("return Math.sqrt(16);")); // 4
console.log(runInSandbox("return JSON.stringify({ a: 1 });")); // '{"a":1}'
 
// Blocked execution
console.log(runInSandbox("return fetch('http://evil.com');"));
// { error: "fetch is not available in sandbox" }
 
// PROPERTY-LEVEL ACCESS CONTROL
function createACLProxy(target, acl) {
  return new Proxy(target, {
    get(t, property, receiver) {
      if (acl.canRead && !acl.canRead(property)) {
        throw new Error(`Read access denied for: ${String(property)}`);
      }
      return Reflect.get(t, property, receiver);
    },
 
    set(t, property, value, receiver) {
      if (acl.canWrite && !acl.canWrite(property)) {
        throw new Error(`Write access denied for: ${String(property)}`);
      }
      return Reflect.set(t, property, value, receiver);
    },
 
    deleteProperty(t, property) {
      if (acl.canDelete && !acl.canDelete(property)) {
        throw new Error(`Delete access denied for: ${String(property)}`);
      }
      return Reflect.deleteProperty(t, property);
    },
 
    ownKeys(t) {
      const keys = Reflect.ownKeys(t);
      if (acl.canRead) {
        return keys.filter((key) => acl.canRead(key));
      }
      return keys;
    },
 
    getOwnPropertyDescriptor(t, property) {
      if (acl.canRead && !acl.canRead(property)) {
        return undefined; // Hide the property
      }
      return Reflect.getOwnPropertyDescriptor(t, property);
    }
  });
}
 
const protectedData = createACLProxy(
  { name: "Alice", ssn: "123-45-6789", email: "alice@example.com" },
  {
    canRead: (prop) => prop !== "ssn",
    canWrite: (prop) => prop !== "ssn" && prop !== "name",
    canDelete: () => false
  }
);
 
console.log(protectedData.name);          // "Alice"
console.log(Object.keys(protectedData));  // ["name", "email"]
// protectedData.ssn;                     // Error: Read access denied

Invariant-Safe Handlers

javascriptjavascript
// Proxy traps must respect invariants or the engine throws TypeError
// Using Reflect ensures invariant compliance
 
// INVARIANT 1: get trap must return the property's value for
// non-writable, non-configurable properties
const strict = {};
Object.defineProperty(strict, "locked", {
  value: 42,
  writable: false,
  configurable: false
});
 
// BAD: Violates invariant
// new Proxy(strict, {
//   get(target, property) {
//     if (property === "locked") return 999; // TypeError!
//     return target[property];
//   }
// });
 
// GOOD: Reflect checks invariants automatically
const safeProxy = new Proxy(strict, {
  get(target, property, receiver) {
    const value = Reflect.get(target, property, receiver);
    // Can still do things with the value, just can't lie about it
    console.log(`Accessed: ${String(property)}`);
    return value; // Must return 42 for 'locked'
  }
});
 
console.log(safeProxy.locked); // 42 (invariant respected)
 
// INVARIANT 2: has trap cannot report a non-configurable own property
// as non-existent
 
// INVARIANT 3: ownKeys must include all non-configurable own properties
 
// INVARIANT 4: getPrototypeOf must return the actual prototype
// if the target is non-extensible
 
// HELPER: Create an invariant-safe handler by wrapping all traps
function safeHandler(traps) {
  const handler = {};
 
  // For each trap, wrap it to fall back to Reflect on error
  for (const [trap, fn] of Object.entries(traps)) {
    handler[trap] = function (...args) {
      try {
        return fn.apply(this, args);
      } catch (error) {
        // If the custom trap would violate an invariant,
        // fall back to default Reflect behavior
        console.warn(`Trap ${trap} violated invariant, using default`);
        return Reflect[trap](...args);
      }
    };
  }
 
  return handler;
}
 
// PATTERN: Debug proxy that reports invariant issues
function createDebugProxy(target, label = "Proxy") {
  return new Proxy(target, {
    get(t, property, receiver) {
      const value = Reflect.get(t, property, receiver);
      if (typeof value === "undefined") {
        console.warn(`[${label}] Property '${String(property)}' is undefined`);
      }
      return value;
    },
 
    set(t, property, value, receiver) {
      const success = Reflect.set(t, property, value, receiver);
      if (!success) {
        console.warn(`[${label}] Failed to set '${String(property)}'`);
      }
      return success;
    },
 
    deleteProperty(t, property) {
      const success = Reflect.deleteProperty(t, property);
      if (!success) {
        console.warn(`[${label}] Failed to delete '${String(property)}'`);
      }
      return success;
    }
  });
}
PatternProxy Traps UsedReflect Methods UsedUse Case
Transparent wrapperAll 13All 13 (forwarding)Debugging, logging
Observableget, set, deleteget, set, deletePropertyState management, UI reactivity
Middlewareget, setget, setValidation, transformation
Sandboxget, set, hasget, set, hasControlled execution
ACLget, set, delete, ownKeysAll correspondingSecurity boundaries
Debugget, set, deleteget, set, deletePropertyDevelopment tooling
Rune AI

Rune AI

Key Insights

  • Always use Reflect methods in Proxy trap handlers for correct forwarding semantics, receiver handling, and invariant compliance: Direct property access in traps breaks inherited accessors and can violate proxy invariants
  • The observable pattern combines Proxy interception (detect changes) with Reflect forwarding (perform changes) for reactive state management: This is the foundation of Vue 3's reactivity system
  • Middleware chains process values through pipelines in set/get traps, using Reflect for the final operation on the target: Each middleware can transform, validate, or block the operation
  • Sandboxed execution uses Proxy has/get traps to control variable access, falling back to Reflect for allowed operations: This creates controlled execution environments with whitelisted globals
  • Invariant-safe handlers rely on Reflect to automatically validate against non-configurable property constraints: The engine enforces invariants on trap return values, and Reflect ensures compliance
RunePowered by Rune AI

Frequently Asked Questions

Why should I always use Reflect in Proxy traps instead of direct access?

Reflect methods handle three critical aspects that direct access misses. First, the receiver parameter ensures correct `this` binding for inherited getters and setters. Second, Reflect methods validate against proxy invariants, preventing TypeErrors from non-configurable property constraints. Third, Reflect methods return proper booleans for set/delete/defineProperty operations, which the engine expects from trap return values. Direct access (target[property], target[property] = value) silently ignores these requirements.

Can I use Reflect without Proxy for practical purposes?

Yes. Reflect.ownKeys is the simplest way to get all property keys (strings and symbols, enumerable and non-enumerable). Reflect.defineProperty returns a boolean instead of throwing, eliminating try-catch for property definition. Reflect.apply is safer than Function.prototype.apply because it cannot be affected by prototype pollution. Reflect.construct with a newTarget enables advanced class instantiation patterns that are not possible with the new operator alone.

How do I handle private class fields with Proxy + Reflect?

Private fields (#field) use internal slots that are bound to the original object, not the proxy. When a method accesses this.#field through a proxy, it fails because the proxy is not the same object. The workaround is to ensure that methods accessing private fields have their `this` bound to the target, not the proxy. In the get trap, check if the returned value is a function and bind it to the target: `if (typeof value === 'function') return value.bind(target)`. This sacrifices reactive property access within methods but preserves private field access.

What is the performance impact of combining Reflect and Proxy?

Using Reflect in Proxy traps adds minimal overhead compared to direct property access in the trap. The major performance cost comes from the Proxy itself (each intercepted operation goes through the trap dispatch), not from using Reflect vs. direct access within the trap. In V8, Reflect.get/set are highly optimized and nearly as fast as target[property]. The recommendation is to always use Reflect for correctness and focus performance optimization on reducing the number of proxied operations rather than optimizing individual trap handlers.

Conclusion

Reflect and Proxy work together to create robust meta-programming patterns. Reflect provides correct default behavior in every Proxy trap through consistent forwarding semantics. The receiver parameter ensures proper inheritance chain behavior. Invariant compliance is handled automatically. For the Proxy API, see Advanced JavaScript Proxies Complete Guide. For WeakMap-based patterns that complement Proxy work, explore JavaScript WeakMap and WeakSet Complete Guide.