Learn how to use JavaScript's Proxy
object to intercept and control object behaviour. Includes real-world use cases like validation, logging, access control, and reactivity.
JavaScript is full of surprises, and one of the most powerful yet underrated features is the Proxy
object. It allows you to intercept, customise, and secure operations on other objects without modifying them directly.
Whether you're building a reactive UI, logging access, or applying security rules, Proxy
can be your best friend.
🔍 What is a JavaScript Proxy?
In simple terms, a Proxy wraps an object and allows you to define custom behaviour for fundamental operations like:
- Reading (
get
) - Writing (
set
) - Deleting (
deleteProperty
) - Function invocation (
apply
) - Enumeration (
ownKeys
) - And more...
💡 Syntax
const proxy = new Proxy(target, handler);
- target: The object you want to proxy.
- handler: An object that defines "traps" (functions that override default behaviour).
💼 Real-World Use Cases for Proxy in JavaScript
1. 📊 Logging Property Access
Want to know when properties are accessed? A Proxy lets you track this easily.
const user = { name: "Adnan", role: "Admin" };
const loggedUser = new Proxy(user, {
get(target, prop) {
console.log(`Property "${prop}" was accessed.`);
return target[prop];
}
});
console.log(loggedUser.name); // Logs: Property "name" was accessed.
2. 🛡️ Validating Property Values
Enforce rules when users update object properties.
const settings = {
volume: 50
};
const validatedSettings = new Proxy(settings, {
set(target, prop, value) {
if (prop === "volume" && (value < 0 || value > 100)) {
throw new Error("Volume must be between 0 and 100");
}
target[prop] = value;
return true;
}
});
validatedSettings.volume = 80; // ✅ OK
validatedSettings.volume = 150; // ❌ Error
3. 🔐 Restricting Access to Sensitive Properties
Block access to confidential data like salary
or SSN
.
const employee = {
name: "Jane",
salary: 7000,
role: "Manager"
};
const secureEmployee = new Proxy(employee, {
get(target, prop) {
if (prop === "salary") {
throw new Error("Access denied to salary");
}
return target[prop];
}
});
console.log(secureEmployee.name); // ✅ "Jane"
console.log(secureEmployee.salary); // ❌ Error
4. 🔄 Auto-Fallback for Missing Properties
No more checking if a key exists—return defaults automatically.
const defaultConfig = new Proxy({}, {
get: (target, prop) => prop in target ? target[prop] : "Not set"
});
console.log(defaultConfig.theme); // "Not set"
defaultConfig.theme = "dark";
console.log(defaultConfig.theme); // "dark"
5. 🚫 Making Objects Immutable
Use Proxies to freeze an object’s properties dynamically.
const constants = {
API_KEY: "12345-SECRET"
};
const immutable = new Proxy(constants, {
set() {
throw new Error("Cannot modify constant values!");
},
deleteProperty() {
throw new Error("Cannot delete properties!");
}
});
immutable.API_KEY = "HACKED"; // ❌ Error
⚙️ Behind the Scenes: How Frameworks Use Proxy
🔄 Vue 3 Reactivity
Vue.js 3 uses Proxy
for its reactivity system, replacing the older Object.defineProperty
approach used in Vue 2.
import { reactive } from 'vue';
const state = reactive({ count: 0 });
state.count++; // Vue tracks changes via Proxy
✅ Benefits of Using Proxy
- 🐞 Debugging: Track object usage.
- 🧼 Validation: Ensure correct data.
- 🛡 Security: Hide sensitive info.
- 🧠 Customization: Dynamic behavior.
- 💡 Fallbacks: Return default values on the fly.
⚠️ Caution When Using Proxy
- Can make debugging harder if misused.
- Slight performance cost compared to plain objects.
- Doesn’t intercept internal slots of built-in types (e.g., Date).
📘 Further Reading
🧵 Final Thoughts
JavaScript Proxies are like magical middlemen—they watch, intercept, and control object behaviour without messing with the original code. Whether you’re developing frameworks, building secure apps, or writing custom logging, Proxies give you superpowers.
Have you used Proxy
in production?
💬 Share your use cases in the comments!
🏷️ Tags
#javascript
#webdev
#frontend
#programming
#vuejs
#codingtips
Top comments (0)