1. Home
  2. Blog
  3. Software Development

Software Development

JavaScript Proxy Explained: All 13 Traps, Reflect and Real Use Cases

A JavaScript proxy wraps an object and lets you intercept what happens to it: reading a property, writing one, deleting one, checking keys, even calling a function. Learn the 13 traps, why Reflect belongs in every handler, eight tested use cases, and three traps of a different kind: private fields, invariants and an 11x slowdown.

9 min read
JavaScript proxy explained: all 13 traps, Reflect and real use cases

Key takeaways

  • A JavaScript proxy is created with new Proxy(target, handler); any trap you leave out forwards straight to the target.
  • Each trap has a matching Reflect method with the same arguments, which performs the default behaviour correctly.
  • Proxying a class with #private fields broke method calls in our test until we bound methods to the target.
  • Reading a property through a proxy with a get trap was about 11 times slower than a plain object in Node 24.

Most JavaScript code just reads and writes object properties. A JavaScript proxy lets you step into the middle of those operations and decide what happens. Vue 3 uses proxies to detect changes and re-render, validation libraries use them to reject bad data, and test tools use them to record every call. Proxies are part of ES2015 and work in every modern browser and in Node.js.

All examples ran in Node.js v24.22.1, and the outputs are copied from the run.

What is a Proxy?

const proxy = new Proxy(target, handler);

The target is the real object. The handler is an object whose methods, called traps, intercept operations. With an empty handler, new Proxy(obj, {}), every operation passes straight through, and the proxy behaves like the target. The proxy is a new object: proxy === target is false, which matters if code compares identities.

All 13 proxy traps

Trap Intercepts
get Reading a property: p.x, p[key]
set Writing a property: p.x = 1
has The in operator
deleteProperty The delete operator
ownKeys Object.keys, for...in, JSON.stringify
getOwnPropertyDescriptor Object.getOwnPropertyDescriptor
defineProperty Object.defineProperty
getPrototypeOf Object.getPrototypeOf, instanceof
setPrototypeOf Object.setPrototypeOf
isExtensible Object.isExtensible
preventExtensions Object.preventExtensions
apply Calling a function proxy: p(1, 2)
construct new p()

The first five cover nearly every real use. apply and construct only work when the target is a function, and typeof a function proxy is still "function".

Why use Reflect inside traps

Reflect is a built-in object with one method per trap, taking exactly the same arguments: Reflect.get(target, key, receiver), Reflect.set(target, key, value, receiver) and so on. Calling it performs the default operation, so a trap can add behaviour and then hand over. It is better than writing target[key] by hand because it passes the receiver along, which keeps getters and inheritance working, and because Reflect.set returns true or false, exactly what a set trap must return.

Use case 1: logging every read and write

const log = [];
const user = { name: "Asha", age: 30 };
const watched = new Proxy(user, {
  get(t, k, r) { log.push(`get ${String(k)}`); return Reflect.get(t, k, r); },
  set(t, k, v, r) { log.push(`set ${String(k)}=${v}`); return Reflect.set(t, k, v, r); },
});
watched.age += 1; watched.name;
// [ 'get age', 'set age=31', 'get name' ]   user.age is now 31

watched.age += 1 triggered a read and then a write, and the change landed on the original object. This is the core of reactive frameworks: record which properties a component reads, and re-run it when one of them is written. String(k) matters because keys can be Symbols, which cannot be inserted into template strings directly.

Use case 2: validating writes

const validated = new Proxy({}, {
  set(t, k, v) {
    if (k === "age" && (!Number.isInteger(v) || v < 0))
      throw new TypeError(`invalid age: ${v}`);
    t[k] = v; return true;
  },
});
validated.age = 41;      // fine
validated.age = -5;      // TypeError: invalid age: -5
validated.age = "old";   // TypeError: invalid age: old

Every assignment passes through one function, so the rule cannot be bypassed by any code holding the proxy. The set trap must return true for success; returning false throws a TypeError in strict mode.

Use case 3: default values for missing properties

const withDefaults = new Proxy({ theme: "dark" }, {
  get: (t, k) => (k in t ? t[k] : "default"),
});
withDefaults.theme, withDefaults.font   // 'dark' 'default'

Instead of undefined, missing settings fall back to a default. The same idea builds configuration objects and can throw on typos instead, which catches bugs like config.timout immediately.

Use case 4: negative array indexes

const arr = new Proxy([10, 20, 30], {
  get(t, k, r) {
    const i = Number(k);
    return Number.isInteger(i) && i < 0 ? t[t.length + i] : Reflect.get(t, k, r);
  },
});
arr[-1], arr[0], arr.length   // 30 10 3

Property keys always arrive as strings, so the trap converts them. Everything that is not a negative integer, including length and array methods, is forwarded with Reflect. Modern code can use the built-in arr.at(-1) instead; this example shows how proxies can add syntax-like behaviour. More array tools are in our JavaScript array methods guide.

Use case 5: hiding private keys

const secret = new Proxy({ id: 1, _token: "x" }, {
  has: (t, k) => !String(k).startsWith("_") && k in t,
  ownKeys: (t) => Reflect.ownKeys(t).filter((k) => !String(k).startsWith("_")),
  deleteProperty(t, k) { if (String(k).startsWith("_")) return false; delete t[k]; return true; },
});
"_token" in secret        // false
Object.keys(secret)       // [ 'id' ]
JSON.stringify(secret)    // {"id":1}
delete secret._token      // strict mode: TypeError 'deleteProperty' on proxy:
                          // trap returned falsish for property '_token'

ownKeys controlled what Object.keys and JSON.stringify saw, has hid the key from in, and deleteProperty refused the deletion. This hides data from casual inspection but is not real security: secret._token still returns "x" because we did not trap get. For truly private data, use class #private fields or a closure.

Use case 6: revocable access

const { proxy, revoke } = Proxy.revocable({ a: 1 }, {});
proxy.a    // 1
revoke();
proxy.a    // TypeError: Cannot perform 'get' on a proxy that has been revoked

A revocable proxy lets you hand an object to untrusted code, such as a plugin, and cut off access later. After revoke(), every operation throws.

Use case 7: wrapping a function

const fn = new Proxy((a, b) => a + b, {
  apply(t, thisArg, args) {
    const r = Reflect.apply(t, thisArg, args);
    return `${args.join("+")}=${r}`;
  },
});
fn(2, 3)   // '2+3=5'

The apply trap sees every call with its arguments, which is how spies in testing libraries record calls, how memoisation wrappers cache results, and how timing wrappers measure functions.

Use case 8: classes with #private fields

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

const pc = new Proxy(new Counter(), {});
pc.inc();
// TypeError: Cannot read private member #n from an object whose class did not declare it

const pc2 = new Proxy(new Counter(), {
  get(t, k) { const v = Reflect.get(t, k); return typeof v === "function" ? v.bind(t) : v; },
});
pc2.inc(), pc2.inc()   // 1 2

This one surprises people. Calling pc.inc() runs inc with this set to the proxy, and the proxy does not have the private field, so even an empty handler failed. The same happens with built-ins that use internal slots, such as Map, Set and Date. Binding methods to the real target in the get trap fixed it. Our guide to the this keyword explains why the receiver matters, and our JavaScript classes guide covers private fields.

Invariants: rules a proxy cannot break

const frozen = Object.freeze({ k: 1 });
const liar = new Proxy(frozen, { get: () => 2 });
liar.k   // TypeError

A proxy cannot lie about the target in ways that would break JavaScript’s guarantees. If a property is non-writable and non-configurable, as every property of a frozen object is, the get trap must return its real value. Our trap returned 2 instead of 1 and the engine threw a TypeError. Similar invariants apply to has, ownKeys, deleteProperty and the others.

The recursion bug: Reflect on the receiver

const rec = new Proxy({ a: 1 }, { get(t, k, r) { return Reflect.get(r, k); } });
rec.a   // RangeError: Maximum call stack size exceeded

The third argument of get, the receiver, is usually the proxy itself. Reading from it calls the get trap again, forever. Always read from the target, Reflect.get(t, k, r), passing the receiver only as the third argument.

The performance cost

Object 10 million property reads
Plain object 25.5 ms
Proxy with empty handler 144.1 ms
Proxy with a get trap calling Reflect 286.9 ms

Even an empty proxy was over five times slower, and a trap made it about 11 times slower, because the engine cannot apply its usual property-access optimisations. A few thousand reads per second will never notice. A hot loop over millions of items will, so unwrap the data or use plain objects in performance-critical code.

Where proxies are used in practice

  • Reactivity: Vue 3 and MobX track reads and writes to update the UI.
  • Validation and schemas: reject bad values at the moment they are assigned.
  • Testing: spies and mocks that record calls, similar to the test doubles in other languages.
  • API clients: api.users.get(1) where users and get are created on the fly by a get trap.
  • Immutable views: a read-only wrapper whose set and deleteProperty traps throw. For deep copies instead, see our JavaScript deep copy guide.

Final thoughts

A JavaScript proxy is a hook into the language itself. Use get and set for most needs, call Reflect on the target inside each trap, and remember the three gotchas we hit: private fields and built-ins need methods bound to the target, invariants on frozen objects cannot be faked, and every intercepted operation costs speed. Applied to configuration, validation, logging or reactive state, proxies replace a lot of repetitive getter and setter code with one small handler.

Frequently asked questions

What is a Proxy in JavaScript?

A Proxy wraps a target object and intercepts operations on it, such as reading, writing or deleting properties, through handler functions called traps. Operations without a trap go straight to the target.

What is the difference between Proxy and Reflect?

Proxy intercepts operations. Reflect performs the default version of each operation, with one method per trap and the same arguments, so traps use Reflect to forward the work correctly.

How many traps does a JavaScript Proxy have?

Thirteen: get, set, has, deleteProperty, ownKeys, getOwnPropertyDescriptor, defineProperty, getPrototypeOf, setPrototypeOf, isExtensible, preventExtensions, apply and construct.

Why does my Proxy break a class with private fields?

Methods run with this set to the proxy, which does not hold the private field. Bind methods to the real target in the get trap, or avoid proxying such classes.

Are JavaScript proxies slow?

They add overhead. In our Node 24 test, 10 million reads took 25 ms on a plain object, 144 ms through an empty proxy and 287 ms through a get trap.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Confusion Matrix Explained: Precision, Recall, F1 and Thresholds in Python

Confusion matrix explained with Python: TP, FP, FN, TN, precision, recall, F1, the accuracy trap, threshold choice by cost and…

Read article →
Software Development

API Pagination: Offset vs Cursor vs Keyset, Tested on 1 Million Rows

API pagination explained: offset vs keyset and cursor pagination timed on 1 million rows, duplicates when data changes, the ties…

Read article →
DevOps

Git Submodule Explained: Add, Clone, Update and Remove Safely

Git submodule explained: add, clone, update –init, update –remote, the detached HEAD trap, foreach and clean removal, tested step by…

Read article →
Test Automation

Pytest tmp path Explained: tmp_path, tmp_path_factory and Temp Files

Pytest tmp_path explained: per-test temporary folders, tmp_path_factory for shared files, monkeypatch.chdir, legacy tmpdir, retention and basetemp.

Read article →
Software Testing

Test Case Prioritization: 6 Techniques Compared With APFD

Test case prioritization compared: risk, coverage, cost, history and random orders scored with APFD and time to find all faults…

Read article →
Databases & SQL

Full Text Search in SQL: FTS5, Ranking, Phrases and Speed

Full text search in SQL with SQLite FTS5: MATCH queries, phrases, prefixes, NEAR, stemming, BM25 ranking, snippets, two gotchas and…

Read article →
Databases & SQL

Generated Columns in SQL: Virtual vs Stored, Indexes and Limits

Generated columns in SQL explained: virtual vs stored, automatic updates, write errors, storage cost, indexing, JSON fields and support in…

Read article →
Software Development

Object Freeze in JavaScript: Shallow vs Deep, Seal and const

Object freeze in JavaScript explained: freeze vs seal vs const, strict mode errors, shallow vs deep freeze, frozen arrays, Map…

Read article →
Software Development

Python hashlib: SHA-256, File Hashes, HMAC and Password Hashing

Python hashlib explained: SHA-256 for strings and files, algorithm speeds, why passwords need PBKDF2 or scrypt, safe verification and HMAC…

Read article →
Software Development

Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys

Python UUID explained: uuid4, uuid5, uuid1 privacy, time-ordered uuid7, parsing, storage formats and UUIDs as database keys, tested on Python…

Read article →
Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →