Software Developer
The Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object.
The Proxy object allows you to create an object that can be used in place of the original object, but which may redefine fundamental Object operations like getting, setting, and defining properties. Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs, and so on.
But how can we use it?
Let's go directly to one example:
const user = {
username: "john_doe",
email: "john@example.com",
password: "superSecret123!",
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
};
const sensitiveFields = ["password", "token"];
const safeUser = new Proxy(user, {
get(target, prop, receiver) {
if (sensitiveFields.includes(prop)) {
return "*** hidden ***";
}
return Reflect.get(target, prop, receiver);
},
ownKeys(target) {
return Reflect.ownKeys(target).filter(key => !sensitiveFields.includes(key));
},
getOwnPropertyDescriptor(target, prop) {
if (sensitiveFields.includes(prop)) {
return undefined;
}
return Reflect.getOwnPropertyDescriptor(target, prop);
},
});
// Accessing properties
console.log(safeUser.username); // john_doe
console.log(safeUser.password); // *** hidden ***
// Listing keys
console.log(Object.keys(safeUser)); // [ 'username', 'email' ]
// Even JSON.stringify respects it
console.log(JSON.stringify(safeUser, null, 2));
/*
{
"username": "john_doe",
"email": "john@example.com"
}
*/
As you can see
console.log(safeUser.username); // john_doe OK
console.log(safeUser.password); // *** hidden *** HIDDEN
In what cases could you use a proxy in JS?
And of course, in many more!
Something cool to learn today!
Let me know what other implementations you could use it in.
(1) Comments
Published 3 days ago
Published 3 days ago
Software Developer
Related Articles
Navigating the Intersection of Business and Technology
Essential tips for avoiding common pitfalls in application development
I've used a proxy object for a while now to intercept all access to a specific global object and log out. For example, sometimes certain user information is cached, so that way, when the user returns again, certain information is already recorded. It's super useful, but not everyone knows about it.