Skip to content

WeakRef and FinalizationRegistry: GC-aware caches (ES2021)

  • How WeakRef.prototype.deref() behaves before and after collection.
  • How FinalizationRegistry callbacks, held values and unregister tokens work, and what is not guaranteed.
  • How to build a cache that reuses large objects only while something else still uses them.

TL;DR: new WeakRef(obj) holds obj without preventing garbage collection; ref.deref() returns the object, or undefined once it has been collected. new FinalizationRegistry(callback) lets you register(obj, heldValue) and have callback(heldValue) called at some point after obj is collected, if the engine chooses to.

Both were added in ECMAScript 2021. Since ECMAScript 2023, non-registered symbols can also be targets. Current browsers and server runtimes support both (see Compatibility). The TC39 proposal’s own advice applies: avoid them if you can. Collection timing is unpredictable and differs between engines, versions and memory conditions.

OrdersPortal parses large quarterly reports. A Map cache keyed by report id avoids parsing twice, but it holds every report forever. A WeakMap does not help here: it holds its keys weakly, and keys must be objects, not id strings.

Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). Samples that force a collection must be run with node --expose-gc sample.mjs; globalThis.gc() is a V8 debugging hook, not a standard API, and real programs never call it. Outputs were produced with Node.js 22.23 and were identical on Node.js 24.22, but collection timing is engine-specific.

const load = (id) => ({ id, rows: new Array(100_000).fill(0) });
// A Map cache holds every report strongly: nothing is ever freed.
const strongCache = new Map();
for (const id of ['2026-Q1', '2026-Q2', '2026-Q3']) strongCache.set(id, load(id));
console.log('Map cache entries:', strongCache.size);
// A WeakMap holds its *keys* weakly, and keys must be objects or non-registered symbols.
try {
new WeakMap().set('2026-Q3', load('2026-Q3'));
} catch (error) {
console.log(`${error.name}: ${error.message}`);
}

Output:

Map cache entries: 3
TypeError: Invalid value used as weak map key

What the cache needs is the reverse: a strong string key and a weak value. That is what WeakRef provides, and FinalizationRegistry removes the empty entries afterwards.

// Run with: node --expose-gc wr-basics.mjs (globalThis.gc is a V8 debugging hook, not a standard API)
const nextTask = () => new Promise((resolve) => setTimeout(resolve, 0));
const registry = new FinalizationRegistry((heldValue) => {
console.log('cleanup callback:', heldValue);
});
let report = { id: 'R-1', rows: new Array(1_000_000).fill(0) };
const ref = new WeakRef(report);
registry.register(report, `report ${report.id} was collected`);
console.log('before:', ref.deref()?.id);
report = null; // drop the only strong reference
await nextTask(); // let the current job finish; deref() keeps its target alive until then
globalThis.gc();
console.log('after gc:', ref.deref());
await nextTask(); // cleanup callbacks run later, as a separate task

Output:

before: R-1
after gc: undefined
cleanup callback: report R-1 was collected

The API is small:

Member What it does
new WeakRef(target) Holds target weakly. target must be an object or a non-registered symbol, otherwise TypeError.
ref.deref() Returns the target, or undefined after collection.
new FinalizationRegistry(callback) Creates a registry; callback(heldValue) may run after a registered target is collected.
registry.register(target, heldValue, unregisterToken?) Watches target. heldValue is held strongly and passed to the callback; it must not be target itself.
registry.unregister(unregisterToken) Removes every registration made with that token; returns true if any were removed.

The specification guarantees read consistency inside one synchronous run of code (a job): new WeakRef(obj) and a deref() that returns an object both keep it alive until the current job finishes. So an object cannot disappear between if (ref.deref()) and ref.deref().method(). Still, read it once into a local variable.

// Run with: node --expose-gc wr-keep.mjs
let session = { user: 'u-42' };
const ref = new WeakRef(session); // creating a WeakRef also keeps the target until the job ends
session = null;
globalThis.gc();
console.log('same job:', ref.deref()?.user); // still alive: kept for the rest of this job
await new Promise((resolve) => setTimeout(resolve, 0));
globalThis.gc();
console.log('next task:', ref.deref()?.user);

Output: same job: u-42, then next task: undefined. This is also why the samples wait for the next task before calling gc().

The specification says an engine may empty a weak reference once its target is unreachable, and may schedule a cleanup job; it is never required to. Callbacks can run late, in batches, or never, for example when the page closes or the process exits. They never run synchronously during gc(), and they run on the same thread as your code. A related cleanupSome() method was split into its own proposal and withdrawn in 2023, so there is no standard way to force cleanup.

The OrdersPortal report cache keeps a WeakRef per report id. While a dashboard holds a report, get() returns the same object without reparsing. Once nothing else uses it, the garbage collector may reclaim it, and the registry callback deletes the empty map entry.

// report-cache.mjs - OrdersPortal: reuse big parsed reports while something still uses them.
// Run with: node --expose-gc report-cache.mjs
export class ReportCache {
#load;
#entries = new Map(); // id -> WeakRef(report)
#registry = new FinalizationRegistry((id) => {
// The id may have been reloaded since; only delete the entry if it is still empty.
if (this.#entries.get(id)?.deref() === undefined) {
this.#entries.delete(id);
this.evicted.push(id);
}
});
evicted = [];
constructor(load) {
this.#load = load;
}
get(id) {
const cached = this.#entries.get(id)?.deref();
if (cached) return cached;
const report = this.#load(id);
this.#entries.set(id, new WeakRef(report));
this.#registry.register(report, id); // held value is the id string, never the report
return report;
}
get size() {
return this.#entries.size;
}
}
let loads = 0;
const cache = new ReportCache((id) => {
loads += 1;
return { id, rows: Array.from({ length: 200_000 }, (_, i) => i) };
});
const pinned = cache.get('2026-Q3'); // a dashboard keeps this one open
cache.get('2026-Q2'); // used once, then dropped
console.log('same object:', cache.get('2026-Q3') === pinned, '| loads:', loads, '| size:', cache.size);
await new Promise((resolve) => setTimeout(resolve, 0));
globalThis.gc();
await new Promise((resolve) => setTimeout(resolve, 0)); // let cleanup callbacks run
console.log('evicted:', cache.evicted, '| size:', cache.size);
cache.get('2026-Q3');
cache.get('2026-Q2');
console.log('loads after re-reading both:', loads, '| pinned still', pinned.id);

Output:

same object: true | loads: 2 | size: 2
evicted: [ '2026-Q2' ] | size: 1
loads after re-reading both: 3 | pinned still 2026-Q3

Three details matter. The callback re-checks deref() because the id might have been reloaded before the old report’s callback ran. The held value is the id string; if it were the report, the registry would keep it alive forever. And the cache stays correct if the callback never runs: it only leaks a few empty entries. In production, pair it with a small strong LRU of recent reports so a collection between two requests does not force a reparse.

  • Using FinalizationRegistry to release resources. File handles, sockets, locks and database connections must be closed explicitly with try...finally or a close() method. The using declarations from the Explicit Resource Management proposal (stage 4, expected in ES2027) are the language-level answer; finalizers are at best a leak detector that logs “you forgot to close this”.
  • Making the held value reference the target. register(obj, obj) throws, but register(obj, { obj }) or a closure that captures obj silently keeps it alive.
  • Calling deref() twice across an await. The keep-alive rule only covers one job. After an await, the object can be gone; read once into a local and use that.
  • Testing timing with gc(). Tests that depend on collection are flaky. Test the cache logic with an injected fake.
  • Registering primitives or registered symbols. new WeakRef(42) and new WeakRef(Symbol.for('id')) throw TypeError, because those values can be recreated and so can never be collected. Unregister tokens follow the same rule.
  • Forgetting unregister. When you dispose an object yourself, call registry.unregister(token) so the callback does not run later. The object itself can be the token.
Need Use
Attach data to an object for as long as the object lives WeakMap (no GC observation needed)
Mark objects as seen without keeping them alive WeakSet
Cache large objects by a string or number key, reusing them while in use WeakRef values plus a FinalizationRegistry to tidy keys
Observers or listeners that should not keep subscribers alive WeakRef to the subscriber, checked on each notification
Release external resources try...finally, close(), or using (not finalizers)
Detect leaks in development FinalizationRegistry logging objects that were collected without being closed

If the program’s correctness would change depending on when, or whether, collection happens, do not use these APIs. They are for memory optimization and diagnostics only.

According to MDN’s browser compatibility data (@mdn/browser-compat-data 8.1.9), WeakRef and FinalizationRegistry are supported in Chrome 84, Edge 84, Firefox 79, Safari 14.1 (iOS 14.5), Node.js 14.6.0, Deno 1.0 and Bun 1.0. Non-registered symbols as targets (ES2023) need Chrome 109, Edge 109, Firefox 146, Safari 16.4, Node.js 20.0.0 and Deno 1.28. Neither API can be polyfilled, because user code cannot observe garbage collection. TypeScript’s types are in lib.es2021.weakref.d.ts.

1. What is the difference between a WeakMap and a WeakRef? A WeakMap holds its keys weakly and its values strongly as long as the key lives; it never lets you observe collection. A WeakRef holds one target weakly, and deref() tells you whether it has been collected. Use WeakMap to attach data to objects; use WeakRef when you need a weak value, such as a cache keyed by a string.

2. Can ref.deref() return an object in one line and undefined on the next? Not within the same synchronous job: creating a WeakRef or getting a target from deref() keeps the target alive until the job ends. Across an await or a timer callback, yes.

3. Is a FinalizationRegistry callback guaranteed to run? No. The specification allows engines to delay callbacks indefinitely or skip them, for example on shutdown or when the registry itself is collected. Code must stay correct if they never run.

4. Why does registry.register(obj, obj) throw, and what is the subtler version of the bug? The held value is kept strongly, so using the target as the held value would keep the target alive forever; the specification rejects it with a TypeError. The subtle version is a held value or callback closure that contains a reference to the target, which is not detected and leaks.

5. Senior scenario: an OrdersPortal browser app keeps a client-side cache of decoded product images and order histories. Memory grows over long sessions. Would you use WeakRef? First measure with heap snapshots to find what actually retains memory. For data with a natural owner object (a component or a DOM node), a WeakMap keyed by the owner is simpler and deterministic. For entries keyed by id, use a bounded strong LRU for recent items, and optionally a WeakRef layer behind it so items still referenced elsewhere are reused instead of reloaded. Use a FinalizationRegistry only to remove empty map entries, re-checking deref() in the callback, and design every path to work if collection never happens. Anything holding real resources (object URLs, workers, sockets) gets explicit release.

  • WeakRef (ES2021) holds a weak value; deref() returns the target or undefined.
  • A target obtained from new WeakRef() or deref() stays alive until the current job ends, but not across await.
  • FinalizationRegistry callbacks are optional, late and unordered: use them for tidying and diagnostics, never for correctness or resource release.
  • Held values are strong; never let them reference the target.
  • Prefer WeakMap, explicit close(), bounded caches and try...finally whenever they solve the problem.