Tutorials JavaScript Proxy & Reflect
Ch 55 / 78
Advertisement
📢 Ad space · 728 × 90 · Replace slot ID above
Chapter 55 Advanced 8 min read JavaScript

Proxy & Reflect

JavaScript's Proxy object lets you intercept and redefine fundamental operations on another object — property reads, writes, deletions, function calls, and more. Reflect is its companion API that provides default implementations of those same operations. Together they unlock powerful metaprogramming patterns: validation layers, reactive systems, access control, and virtual objects — all without modifying the original object.

What you'll learn
What a Proxy is and how it wraps a target object
All 13 handler traps — get, set, has, deleteProperty & more
How the Reflect API mirrors every Proxy trap
Building validation, logging, and access-control proxies
Revocable proxies and when to use them
Real-world patterns — reactive state, memoization, API mocking

Three Building Blocks of Proxy & Reflect

Every Proxy interaction involves exactly three participants. Knowing each role prevents confusion when reading or writing proxy code:

Target
The Original Object
The real object (or function) being wrapped. All proxy traps operate on behalf of the target. The target itself is unchanged — the proxy sits in front of it.
Example: a plain {}, an array, a class instance, or even another Proxy
Handler / Traps
The Interceptor
A plain object whose methods — called traps — override default object operations. Each trap corresponds to one internal JavaScript operation (e.g., [[Get]], [[Set]]).
Traps: get, set, has, deleteProperty, apply, construct, ownKeys…
Reflect
The Default Behaviour
A built-in object with static methods that mirror every Proxy trap. Use Reflect.get() inside a trap to call the original operation after your custom logic runs.
Methods: Reflect.get, Reflect.set, Reflect.has, Reflect.deleteProperty…

Anatomy of a Proxy

Creating a Proxy takes exactly two arguments — the target and the handler. Here is the smallest possible example — an empty handler that passes every operation straight through to the target:

// Syntax — new Proxy(target, handler)
const target = { name: "Alice", age: 30 };

const handler = {
  get(target, prop) {
    console.log(`Reading "${prop}"`);
    return Reflect.get(target, prop); // default behaviour
  }
};

const proxy = new Proxy(target, handler);
proxy.name; // logs: Reading "name" → "Alice"
target — the real object being wrapped handler — object with trap methods Reflect.get — calls original [[Get]] operation proxy — the public-facing intercepted object
JavaScript — Basic Proxy
// ── Transparent proxy — no traps, passes everything through ───
const raw = { x: 10, y: 20 };
const p1 = new Proxy(raw, {});              // empty handler
console.log(p1.x);                          // 10

// ── get trap — intercept property reads ──────────────────────
const p2 = new Proxy(raw, {
  get(target, prop, receiver) {
    console.log(`get: ${prop}`);
    return Reflect.get(target, prop, receiver);
  }
});
p2.x;                                     // logs: get: x → 10

// ── set trap — intercept property writes ─────────────────────
const p3 = new Proxy({}, {
  set(target, prop, value) {
    if (typeof value !== "number") throw new TypeError("Numbers only!");
    return Reflect.set(target, prop, value);
  }
});
p3.score = 42;                             // ✅ OK
p3.score = "hello";                      // ❌ TypeError: Numbers only!

The 13 Proxy Traps

A handler object can define up to 13 trap methods. Each trap intercepts one internal JavaScript operation. The most frequently used traps are get, set, and has:

Property Traps
1 get(target, prop, receiver) — fires on proxy.prop reads
2 set(target, prop, value, receiver) — fires on proxy.prop = val
3 has(target, prop) — fires on prop in proxy
4 deleteProperty(target, prop) — fires on delete proxy.prop
5 ownKeys(target) — fires on Object.keys(proxy)
6 getOwnPropertyDescriptor(target, prop) — fires on Object.getOwnPropertyDescriptor()
7 defineProperty(target, prop, desc) — fires on Object.defineProperty()
Object & Function Traps
8 apply(target, thisArg, args) — fires when the proxy itself is called as a function
9 construct(target, args, newTarget) — fires on new proxy()
10 getPrototypeOf(target) — fires on Object.getPrototypeOf(proxy)
11 setPrototypeOf(target, proto) — fires on Object.setPrototypeOf(proxy, …)
12 isExtensible(target) — fires on Object.isExtensible(proxy)
13 preventExtensions(target) — fires on Object.preventExtensions(proxy)
JavaScript — Common Traps in Action
const data = { name: "Bob", _secret: "hidden" };

const safeProxy = new Proxy(data, {
  // 1. get — block private props (starting with _)
  get(target, prop) {
    if (prop.startsWith("_")) throw new Error("Access denied");
    return Reflect.get(target, prop);
  },

  // 2. set — type-check before writing
  set(target, prop, value) {
    if (prop === "name" && typeof value !== "string")
      throw new TypeError("name must be a string");
    return Reflect.set(target, prop, value);
  },

  // 3. has — hide private props from 'in' operator
  has(target, prop) {
    if (prop.startsWith("_")) return false;
    return Reflect.has(target, prop);
  },

  // 4. deleteProperty — protect certain keys
  deleteProperty(target, prop) {
    if (prop === "name") throw new Error("Cannot delete name");
    return Reflect.deleteProperty(target, prop);
  }
});

safeProxy.name;                          // ✅ "Bob"
safeProxy._secret;                      // ❌ Error: Access denied
"_secret" in safeProxy;               // false (hidden)

The Reflect API

Reflect is a built-in object (not a constructor — you cannot use new Reflect()) that provides static methods corresponding to every JavaScript internal operation. Its two main purposes are:

Why use Reflect inside traps?
(1) It correctly handles the receiver argument for getters/setters that rely on prototypes — something a plain target[prop] access does not do. (2) It returns a boolean (true/false) for operations like set and deleteProperty, which is what traps are expected to return to signal success or failure to the runtime.
JavaScript — Reflect API Methods
const obj = { a: 1, b: 2 };

// Reflect.get — like obj[prop] but receiver-aware
Reflect.get(obj, "a");                       // 1

// Reflect.set — returns true/false (unlike direct assignment)
Reflect.set(obj, "c", 3);                   // true

// Reflect.has — like 'prop in obj'
Reflect.has(obj, "a");                       // true

// Reflect.deleteProperty — like delete obj.prop
Reflect.deleteProperty(obj, "b");         // true

// Reflect.ownKeys — all own keys (string + symbol)
Reflect.ownKeys(obj);                       // ["a", "c"]

// Reflect.apply — like fn.apply(thisArg, args)
const sum = (a, b) => a + b;
Reflect.apply(sum, null, [3, 4]);           // 7

// Reflect.construct — like new Target(...args)
class Point { constructor(x, y) { this.x = x; this.y = y; } }
Reflect.construct(Point, [1, 2]);         // Point {x:1, y:2}
Operation Old Way Reflect Equivalent Returns Notes
Read obj[prop] Reflect.get(obj, prop) value Receiver-aware for getters
Write obj[prop] = val Reflect.set(obj, prop, val) boolean Returns false in strict mode failures
Check prop in obj Reflect.has(obj, prop) boolean Walks prototype chain
Delete delete obj.prop Reflect.deleteProperty(obj, prop) boolean No TypeError in non-strict mode
Call fn fn.apply(this, args) Reflect.apply(fn, this, args) return val Safer — fn.apply can be overridden
Construct new Fn(...args) Reflect.construct(Fn, args) instance Supports optional newTarget

Revocable Proxies

Proxy.revocable() creates a proxy that can be permanently disabled. After calling revoke(), any further access to the proxy throws a TypeError. This is useful for temporarily granting access to sensitive data, then revoking it when a task completes:

// ❌ PROBLEM: once you share an object, you cannot take it back
const secret = { token: "abc-123" };
someLibrary.use(secret); // library now holds a direct reference forever

// ✅ BETTER: pass a revocable proxy, revoke when done
const { proxy, revoke } = Proxy.revocable(secret, {});
someLibrary.use(proxy);
revoke(); // proxy is now dead — any access throws TypeError
JavaScript — Revocable Proxy
const { proxy, revoke } = Proxy.revocable({ data: 42 }, {
  get(target, prop) {
    console.log(`Accessing ${prop}`);
    return Reflect.get(target, prop);
  }
});

console.log(proxy.data);                  // logs: Accessing data → 42

revoke();                               // disable the proxy

try {
  proxy.data;                          // ❌ TypeError: Cannot perform 'get'
} catch (e) {
  console.error(e.message);
}

Key Method Reference

These are the Proxy traps and Reflect methods you'll reach for in virtually every real-world use case. Bookmark this list:

new Proxy(target, handler)
Creates a proxy wrapping target. Every operation on the proxy first passes through the matching trap in handler, if defined.
handler.get(target, prop, receiver)
Intercepts property reads — proxy.prop, proxy["prop"], destructuring, and Reflect.get. The receiver is the object the operation was originally directed at (important for inheritance).
handler.set(target, prop, value, receiver)
Intercepts property writes. Must return true on success or false on failure — returning nothing causes a TypeError in strict mode.
handler.has(target, prop)
Intercepts the in operator. Return a boolean. Useful for hiding properties from enumeration while keeping them accessible via direct reads.
handler.apply(target, thisArg, args)
Intercepts function calls — proxy(), proxy.call(), proxy.apply(). The target must be a callable (function); otherwise a TypeError is thrown.
Proxy.revocable(target, handler)
Returns { proxy, revoke }. Calling revoke() permanently disables the proxy. Any subsequent access throws a TypeError. Perfect for temporary capability grants.
Reflect.get / set / has / deleteProperty
Always prefer these inside traps over direct target[prop] access — they correctly forward the receiver and return the boolean results that traps are expected to return.
Reflect.ownKeys(target)
Returns all own property keys — both string and Symbol keys — of the target. Unlike Object.keys() it also includes non-enumerable and Symbol-keyed properties.
Advertisement
📢 Ad space · 728 × 90 · Replace slot ID above

Real-World Use Cases

Here are the patterns you'll encounter Proxy used for in real JavaScript projects and frameworks:

Schema Validation
Use a set trap to validate every property write against a schema — type, range, or format — before it reaches the object.
set trap
Reactive / Observable State
Fire UI re-renders or callbacks automatically whenever state changes — the approach used internally by Vue 3's reactivity system.
get + set traps
Access Control
Block reads or writes to private properties (e.g., those starting with _) using get, set, and has traps.
get + has traps
Property Logging
Transparently log every read and write to an object — invaluable for debugging state mutations in complex applications.
get + set traps
Memoization Cache
Wrap a function with an apply trap that caches results by arguments — returning cached values instantly on repeated calls.
apply trap
API Mocking / Default Values
Return sensible defaults for missing properties instead of undefined — useful for mocking deeply nested API responses in tests.
get trap
⚡
Free Resource
Download our JavaScript Cheat Sheet
Proxy traps, Reflect API & metaprogramming patterns — all on one page.
Get Sheet

Try It — Live Editor

Experiment with Proxy below. The demo builds a reactive counter object — any write to it automatically logs the change. Edit the handler and run to see your result.

Live Editor
✎ Editor
👁 Preview

Common Patterns

Three patterns you will see repeatedly in real codebases that use Proxy:

JavaScript — Pattern 1: Default Values
// Return a default value for any missing property instead of undefined
function withDefaults(target, defaults) {
  return new Proxy(target, {
    get(t, prop, receiver) {
      return Reflect.has(t, prop)
        ? Reflect.get(t, prop, receiver)
        : defaults[prop];
    }
  });
}

const config = withDefaults({ theme: "dark" }, { theme: "light", lang: "en" });
config.theme;                            // "dark" (from target)
config.lang;                             // "en" (from defaults)
JavaScript — Pattern 2: Memoization with apply trap
function memoize(fn) {
  const cache = new Map();
  return new Proxy(fn, {
    apply(target, thisArg, args) {
      const key = JSON.stringify(args);
      if (cache.has(key)) {
        console.log("cache hit");
        return cache.get(key);
      }
      const result = Reflect.apply(target, thisArg, args);
      cache.set(key, result);
      return result;
    }
  });
}

const slowSquare = n => { return n * n; }; // imagine it's slow
const fastSquare = memoize(slowSquare);
fastSquare(9);  // computed: 81
fastSquare(9);  // cache hit → 81
JavaScript — Pattern 3: Reactive State (Vue 3 style)
function reactive(obj, onChange) {
  return new Proxy(obj, {
    set(target, prop, value) {
      const old = target[prop];
      const ok = Reflect.set(target, prop, value);
      if (ok && old !== value) onChange(prop, old, value);
      return ok;
    }
  });
}

const store = reactive({ count: 0, name: "App" }, (prop, old, val) => {
  console.log(`[CHANGE] ${prop}: ${old} → ${val}`);
  // trigger UI re-render here
});

store.count++;  // [CHANGE] count: 0 → 1
store.name = "MyApp";  // [CHANGE] name: App → MyApp
Performance Note
Proxies add a small overhead to every trapped operation because the engine must call your JavaScript trap function instead of running the native C++ operation directly. For hot code paths (tight loops, high-frequency render cycles) benchmark your proxy before shipping. For most application code the overhead is negligible.
Quick Check
Which Proxy trap fires when you write prop in proxy?
Quick Check
Why should you use Reflect.set() inside a set trap instead of writing target[prop] = value directly?
Chapter Summary
  • A Proxy wraps a target object and intercepts its internal operations via handler traps — without modifying the original object.
  • There are 13 traps. The most common are get, set, has, deleteProperty, apply, and ownKeys.
  • Always call the matching Reflect method inside a trap to perform the default operation — it correctly handles the receiver and returns the boolean that traps must return.
  • The set trap must return true on success (or call Reflect.set() which does this for you) — failing to return truthy causes a TypeError in strict mode.
  • Proxy.revocable() creates a proxy with a paired revoke() function. After revocation all access throws a TypeError — ideal for temporary capability delegation.
  • Common real-world uses: schema validation, reactive/observable state (Vue 3 reactivity), access control, property logging, memoization, and default values.
  • Proxy adds a small per-operation overhead. It is negligible in typical application code but benchmark before using in performance-critical loops.
  • You cannot proxy primitive values — only objects, arrays, functions, and other proxies.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel