Loading...
Baldur O. 🧠

Baldur O. 🧠

Software Developer

Did you know about Proxy on JavaScript?

The Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object.

Published 9 days ago Viewed 16 times

The official description says

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?

  • Sensitive Data Protection (like the previous example)
  • Form Validation with Dynamic Rules
  • Localization / Internationalization
  • API Request Caching (I love this one)

And of course, in many more!
Something cool to learn today!
Let me know what other implementations you could use it in.

(1) Comments

Alex Chav

Alex Chav

Published 3 days ago

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.

Baldur O. 🧠

Baldur O. 🧠 Author

Published 3 days ago

Replied to Alex Chav

Great approach Alex, thank you!

Baldur O. 🧠
Baldur O. 🧠

Baldur O. 🧠

Software Developer

Who commented on this post

More from Baldur O. 🧠

Related Articles

Follow @GoConnect for insights and stories on building profitable online businesses, and connect with fellow entrepreneurs in the GoConnect community.