Sub topic 7
FinalizationRegistry and Cleanup Callbacks
A WeakRef lets you check whether an object is still alive, but only when you ask. FinalizationRegistry works the other way around. You give it a callback, and the engine may call that callback after an object you registered has been garbage collected. This chapter covers the constructor, the register() method, how the cleanup callback is invoked, and the rules the engine enforces when you register.
This chapter assumes you know objects, closures, and the event loop at a conceptual level, and that you have read the earlier chapters on reachability and WeakRef. Held values, unregister tokens, and timing guarantees each get a chapter of their own later. Here they appear only as far as you need them to use the API correctly.
The Shape of the API
A FinalizationRegistry has one constructor argument and two methods:
| Member | Signature | Returns | Purpose |
|---|---|---|---|
| Constructor | `new FinalizationRegistry(callback)` | registry | Stores the cleanup callback |
| `register` | `register(target, heldValue, unregisterToken?)` | `undefined` | Watches `target`; passes `heldValue` to the callback later |
| `unregister` | `unregister(unregisterToken)` | `boolean` | Removes registrations made with that token |
The callback receives a single argument, which is the held value supplied at registration. It never receives the target, because the target no longer exists when the callback runs. If the engine could hand you the target, it would have to bring a collected object back to life, and the design rules that out.
const registry = new FinalizationRegistry((heldValue) => {
console.log(`Cleaned up: ${heldValue}`);
});
let resource = { id: 42 };
registry.register(resource, 'resource-42');
resource = null; // at some later point the callback may run with 'resource-42'After resource = null, nothing strongly refers to the { id: 42 } object. The registry refers to it only weakly. Once the collector reclaims it, the engine may queue a job that calls the callback with 'resource-42'.
What the Registry Holds, and How Strongly
The registry holds different parts of each registration with different strengths, and getting this wrong is behind most surprising behavior.
| Part | Held by the registry | Consequence |
|---|---|---|
| The callback | Strongly | Anything the callback's closure captures stays alive as long as the registry does |
| The target | Weakly | Registration does not prevent collection |
| The held value | Strongly | Must not refer back to the target, or the target never becomes unreachable |
| The unregister token | Weakly | Registering does not keep the token alive |
The registry itself is an ordinary object. If your program drops every reference to the registry, the registry can be collected too, and its pending callbacks may never run. Keep registries in a long-lived place such as a module-level constant or a static class field. Do not create one per call inside a function.
// Fragile: the registry may be collected along with its callbacks.
function track(obj) {
const registry = new FinalizationRegistry((label) => console.log(label));
registry.register(obj, 'tracked');
}
// Robust: one registry that lives as long as the module.
const trackingRegistry = new FinalizationRegistry((label) => console.log(label));
function trackReliably(obj) {
trackingRegistry.register(obj, 'tracked');
}The Lifecycle of a Registration
Each call to register() creates one registration record. A record has three possible endings. The engine cleans it up and calls the callback once. Your code removes it with unregister(). Or nothing happens, because the program exits or the registry is collected first.
The NeverRun path is legal behavior, not a bug. A later chapter covers what the engine does not promise. For now, keep in mind that a callback is something that might happen. Your program cannot rely on it.
How the Callback Is Invoked
The cleanup callback never interrupts running code. When the collector reclaims registered targets, the engine asks the host (the browser or Node.js) to schedule a cleanup job. That job runs later, on the event loop, as its own turn. Your synchronous code, and the microtasks queued from it, finish before any cleanup callback starts.
This invocation model has a few practical consequences:
- Each registration produces at most one callback call. If several targets are collected together, the engine may handle them in one cleanup job, with one callback call per registration.
- The order of callbacks across registrations is unspecified. Do not assume that objects registered first are finalized first.
- An exception thrown from the callback is reported through the host's usual error path. In Node.js, that is the same path as an uncaught exception from a timer, which by default crashes the process. Wrap risky cleanup code in
try/catch. - The callback can do ordinary work, such as logging, deleting map entries, or calling
unregister(). It cannot get the collected object back.
const registry = new FinalizationRegistry((key) => {
try {
releaseNativeSlot(key);
} catch (err) {
console.error(`Cleanup for ${key} failed:`, err);
}
});
function releaseNativeSlot(key) {
if (typeof key !== 'string') throw new Error('bad key');
console.log(`released ${key}`);
}
registry.register({}, 'slot-1');Validation Rules in register()
register() checks its arguments synchronously and throws a TypeError when a rule is broken. Each rule exists to stop a registration that could never work.
| Rule | Why |
|---|---|
| `target` must be an object or a non-registered symbol | Primitives and `Symbol.for()` symbols are never collected, so a callback could never fire |
| `heldValue` must not be the same value as `target` | The registry holds the held value strongly, so the target would stay alive forever |
| `unregisterToken`, if given, must be an object or a non-registered symbol | Tokens are held weakly, so they must be values that can be held weakly |
| `unregisterToken` may be omitted or `undefined` | The registration then cannot be cancelled |
The script below checks each rule. Run it with node or paste it into a browser console.
const registry = new FinalizationRegistry(() => {});
function attempt(label, fn) {
try {
fn();
console.log(`${label}: ok`);
} catch (err) {
console.log(`${label}: ${err.constructor.name}`);
}
}
const obj = {};
attempt('object target', () => registry.register({}, 'x'));
attempt('primitive target', () => registry.register(42, 'x'));
attempt('registered symbol target', () => registry.register(Symbol.for('app'), 'x'));
attempt('unique symbol target', () => registry.register(Symbol('local'), 'x'));
attempt('held value === target', () => registry.register(obj, obj));
attempt('primitive token', () => registry.register({}, 'x', 'token'));
attempt('object token', () => registry.register({}, 'x', {}));
attempt('no held value', () => registry.register({}));Expected output in engines that support symbols as weak targets (Node.js 20 and later, current browsers):
object target: ok
primitive target: TypeError
registered symbol target: TypeError
unique symbol target: ok
held value === target: TypeError
primitive token: TypeError
object token: ok
no held value: okThe held value === target check catches only the direct case. A held value such as { owner: obj } passes validation but still keeps obj alive forever. The engine cannot detect that indirect cycle, and the pitfalls chapter comes back to it.
Registering the Same Target More Than Once
You can register one target several times, in one registry or in several. Each call creates an independent record, and each record can produce its own callback call with its own held value.
const registry = new FinalizationRegistry((label) => {
console.log(`finalized: ${label}`);
});
let shared = { data: new Array(1000).fill(0) };
registry.register(shared, 'first registration');
registry.register(shared, 'second registration');
shared = null;
// If the object is collected, the callback may run twice:
// once with 'first registration' and once with 'second registration'.This is useful when separate subsystems each need to clean up their own state for the same object. It also means that calling register() repeatedly by accident, for example on every cache hit, leads to duplicate cleanup. Register once, at the point where the object is created or first tracked.
Choosing What to Register
A finalization callback fits only when all of these hold:
- Something outside the target needs updating after the target is gone. Examples are a map entry, a counter, or a native handle.
- The cleanup is not required for correctness. The program still behaves correctly if the callback runs late or never runs.
- The data the cleanup needs can be held separately from the target, as a held value that does not refer back to it.
When the first condition fails, there is nothing to do and no reason to register. When the second fails, explicit cleanup is the right tool, as discussed in the final chapter. When the third fails, restructure the object first so that the resource it wraps can be held separately.
Exercise
A developer writes const r = new FinalizationRegistry(cb); r.register(node, node.id); inside a function that runs once per DOM node, creating a new registry each time. Callbacks rarely fire. Identify the problem and the fix.
Show answer
Each registry is a local value that becomes unreachable when the function returns, so it can be collected along with its pending registrations, and their callbacks never run. Create one registry at module level and reuse it for every node. Using node.id, a primitive, as the held value is fine because it does not refer back to the node.
Exercise
Which of these calls throw a TypeError? (a) registry.register({}, 5) (b) registry.register('str', {}) (c) registry.register(o, o) (d) registry.register(o, { o }) (e) registry.register(o, 'x', Symbol.for('t'))
Show answer
(b) throws because a string is not a valid target. (c) throws because the held value is the target. (e) throws because a registered symbol is not a valid unregister token. (a) and (d) succeed, but (d) keeps o alive forever because the held value strongly refers to it, so its callback never runs.
Exercise
A cleanup callback throws an error in Node.js. What happens, and how should the callback be written to prevent it?
Show answer
The error is reported like an uncaught exception, which by default terminates the Node.js process. Wrap the body of the callback in try/catch and log or otherwise handle failures inside it.
Exercise
An object is registered twice in the same registry with held values 'a' and 'b', and is then collected. How many times can the callback run, and in what order?
Show answer
Up to twice, once with 'a' and once with 'b', because each registration is independent. The order is unspecified, and either call, or both, may never happen.