Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 32

WeakMap for Private Proxy Metadata

This lesson is built with resources from youtube.com, developer.mozilla.org and 1 more site.

Hello! Welcome to the final lesson in our module on Metaprogramming with Proxies and Reflect.

In our last lesson, we explored revocable proxies, which provide a mechanism to grant and then later rescind access to an object. We ended with a practical challenge: if you create many revocable proxies, how do you associate each proxy with its corresponding revoke function without exposing the function itself? We saw a brief preview of a solution using a WeakMap.

Today, we'll dive deep into that solution. Our learning outcome is to use a WeakMap in a proxy handler to store private metadata without causing memory leaks. This is a cornerstone advanced JavaScript pattern that combines metaprogramming with a nuanced understanding of JavaScript's memory model. It allows you to attach hidden information to objects in a robust and memory-safe way.

The Problem: Associating Data and Avoiding Memory Leaks

Let's first establish why this is a non-trivial problem. Imagine you want to associate some metadata with an object. A natural first thought, given your programming background, might be to use a hash map. In JavaScript, this is the Map object.

let metadata = new Map();

let user = { id: 1, name: "John Doe" };
metadata.set(user, { lastLogin: "2023-10-27" });

// We can retrieve the metadata
console.log(metadata.get(user)); // { lastLogin: '2023-10-27' }

// Now, let's say the user logs out and we no longer need the object.
user = null;

What happens to the { id: 1, name: "John Doe" } object in memory? Although we've nulled out our user variable, the metadata Map still holds a reference to that object as a key. This is a strong reference.

JavaScript's garbage collector operates on a principle called "reachability." An object is kept in memory as long as it is "reachable" from a root (like the global object). Since our metadata map is still reachable, and it holds a strong reference to the user object, that object is also considered reachable. It will not be garbage collected. This is a classic memory leak. Over time, your map could fill up with metadata for objects that are no longer used anywhere else in your application.


The Solution: Weak References and WeakMap

To solve this, JavaScript provides WeakMap. It behaves similarly to a Map, but with one crucial difference: it holds weak references to its keys. A weak reference does not prevent an object from being garbage collected.

To understand this distinction clearly, let's watch a short, excellent explanation.

What are WeakMaps? #javascript #programming

This video from Lydia Hallie provides a very clear and concise contrast between Map and WeakMap and their relationship with the garbage collector.

Watch the full video. Pay close attention to how a strong reference in a Map prevents garbage collection, whereas a weak reference in a WeakMap allows it.

As the video explains, if we use a WeakMap instead:

  1. We create an object user and use it as a key in a WeakMap.
  2. The WeakMap now has a weak reference to the user object.
  3. When we set user = null, the only remaining reference to the object is the weak one inside the WeakMap.
  4. The garbage collector sees that there are no more strong references to the object, so it is free to reclaim that memory.
  5. When the key object is garbage collected, the entire entry (key and value) is automatically removed from the WeakMap.
WeakMap Garbage Collection Demonstration
This console screenshot demonstrates the behavior of a `WeakMap`. After the strong reference to object `a` is removed (`a = null`) and garbage collection is manually triggered (`gc()`), the `WeakMap` becomes empty, proving that the entry associated with the now-collected object has been removed automatically.

This automatic cleanup has an important consequence: WeakMaps are not enumerable. You cannot iterate over their keys or values (e.g., with forEach) or ask for their size. Since the garbage collector can run at any time, an entry could disappear in the middle of an iteration, leading to non-deterministic and unreliable behavior.

WeakMap - JavaScript - MDN Web Docs

For a formal definition and a deeper dive into the 'why', the MDN Web Docs are an invaluable resource. This will solidify your theoretical understanding.

Read the main description at the top of the page, and then the section 'Why WeakMap?'. Focus on why keys must be objects and why enumeration is not supported.


The Pattern: Combining Proxy and WeakMap

Now we have all the pieces. We can combine Proxy and WeakMap to create an elegant pattern for private object state.

The strategy is:

  1. Create a WeakMap inside a closure to store the private data. This makes the WeakMap itself inaccessible to the outside world.
  2. The keys of the WeakMap will be the target objects.
  3. The values will be objects containing the private data we want to associate.
  4. Create a Proxy that intercepts operations (like get and set). The proxy handler will have access to the WeakMap via its closure.
  5. Inside the traps, use the target object to look up its private data in the WeakMap and act accordingly.

Let's see this in practice.

The Secrets of Proxies: Proxies with WeakMap for Private Data

This article from dev.to provides a perfect, practical example of this pattern. It implements a SecureUser class where sensitive information is stored in a WeakMap and managed by a Proxy.

Focus on the code block under the heading 'Proxies with WeakMap for Private Data' and the accompanying explanation. Analyze how the privateData WeakMap is initialized and used within the proxy's get trap.

Let's break down that SecureUser example:

const privateData = new WeakMap();

class SecureUser {
  constructor(name, password) {
    // 1. Create the private data object
    const data = {
      name,
      password,
      passwordAttempts: 0
    };
    
    // 2. Associate this instance with its private data
    privateData.set(this, data);

    // 3. Return a proxy, not the instance itself!
    return new Proxy(this, {
      get(target, prop) {
        // The 'target' here is the original SecureUser instance
        
        // 4. Intercept access to 'name'
        if (prop === 'name') {
          return privateData.get(target).name;
        }

        // 5. Intercept access to 'checkPassword' and return a custom function
        if (prop === 'checkPassword') {
          return (passwordGuess) => {
            const data = privateData.get(target);
            data.passwordAttempts++;
            if (data.passwordAttempts > 3) {
              throw new Error('Account locked after multiple attempts');
            }
            return data.password === passwordGuess;
          };
        }
        
        // 6. Forward any other property access
        return Reflect.get(target, prop);
      }
    });
  }
}

const user = new SecureUser('john', 'password123');

console.log(user.name); // 'john'
console.log(user.password); // undefined -> The private data is inaccessible

// user becomes eligible for GC, and its entry in `privateData` will also be removed.
// let user = null; 

This pattern provides:

  • True Encapsulation: The password and passwordAttempts are impossible to access from outside the proxy handler. The privateData WeakMap is hidden in the module's scope.
  • Memory Safety: When the user proxy and the original SecureUser instance are no longer referenced, they become eligible for garbage collection. The WeakMap's weak reference ensures it won't prevent this cleanup.
Test your understanding!

Let's revisit the problem from our last lesson. We wanted to manage the revoke function for a revocable proxy.

Using the Proxy/WeakMap pattern, create a RevocableProxyManager class that does the following:

  1. A create(target) method that takes an object, creates a revocable proxy for it, stores the revoke function in a private WeakMap (with the proxy as the key), and returns the proxy.
  2. A revoke(proxy) method that looks up the given proxy in the WeakMap, calls its associated revoke function if found, and removes it from the map.
// You should be able to use your class like this:
const manager = new RevocableProxyManager();

const obj1 = { data: "first" };
const proxy1 = manager.create(obj1);

console.log(proxy1.data); // "first"

manager.revoke(proxy1);

try {
  console.log(proxy1.data);
} catch(e) {
  console.error(e.message); // Should throw a TypeError
}
Show answer

Here is a complete implementation:

class RevocableProxyManager {
  // #revokers is a private field, which also works.
  // But for this exercise, we'll use a closure-scoped WeakMap.
  #revokers = new WeakMap();

  create(target) {
    const { proxy, revoke } = Proxy.revocable(target, {});
    
    // The key is the proxy object itself.
    // The value is the function to revoke it.
    this.#revokers.set(proxy, revoke);
    
    return proxy;
  }

  revoke(proxy) {
    const revokeFn = this.#revokers.get(proxy);
    if (revokeFn) {
      revokeFn();
      this.#revokers.delete(proxy); // Clean up the map
      console.log("Proxy has been revoked.");
      return true;
    }
    console.log("Proxy not found or already revoked.");
    return false;
  }
}


const manager = new RevocableProxyManager();

const obj1 = { data: "first" };
const proxy1 = manager.create(obj1);

console.log(proxy1.data); // "first"

manager.revoke(proxy1); // "Proxy has been revoked."

try {
  console.log(proxy1.data);
} catch(e) {
  console.error(e.message); // "Cannot perform 'get' on a proxy that has been revoked"
}

This demonstrates how WeakMap is the perfect tool for associating private, side-channel information with an object without interfering with its memory lifecycle.


Conclusion

This lesson concludes our module on metaprogramming. You've learned how to intercept and redefine the fundamental operations of objects, control access lifecycles, and now, how to attach private metadata in a memory-safe way. This is a powerful combination of techniques for building secure, robust, and complex APIs and frameworks.

Key Takeaways:

  • Map creates strong references to its keys, which can prevent garbage collection and lead to memory leaks.
  • WeakMap creates weak references to its keys, allowing objects to be garbage collected when no other strong references exist. Consequently, WeakMap is not iterable.
  • The pattern of using a WeakMap within a closure, accessed by a Proxy's handler, is the canonical way to associate private metadata with an object without causing memory leaks.
  • The proxy becomes the public-facing interface, while the WeakMap acts as a private, side-channel lookup table.

Next Up

Congratulations on completing the Metaprogramming module! We've just explored a sophisticated way to emulate private properties. In our next module, "Advanced OOP: Classes and Encapsulation," we will explore how modern JavaScript provides a native, built-in syntax for this exact purpose: private class fields (#). We will contrast the pros and cons of the native approach versus the Proxy/WeakMap pattern you've just mastered.