javascript / expert
Snippet
WeakRef and FinalizationRegistry for Cache Eviction Tracking in Next.js Server Components
Using WeakRef combined with FinalizationRegistry allows Next.js server component caches to retain references without blocking Garbage Collection, enabling runtime lifecycle diagnostics when transient payload memory is reclaimed.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const registry = new FinalizationRegistry((heldKey) => {console.warn(`[GC Eviction] Memory released for key: ${heldKey}`);});const serverCache = new Map();export function setTrackedCache(key, heavyObject) {const ref = new WeakRef(heavyObject);serverCache.set(key, ref);registry.register(heavyObject, key);}export function getTrackedCache(key) {const ref = serverCache.get(key);return ref ? ref.deref() : undefined;}
nextjs
Breakdown
1
const ref = new WeakRef(heavyObject);
Creates a weak reference wrapper around an object, preventing the reference from impeding garbage collection.
2
registry.register(heavyObject, key);
Registers a cleanup callback target that fires asynchronously when the underlying object is garbage collected.
3
return ref ? ref.deref() : undefined;
Attempts to resolve the target object; returns undefined if the engine has collected the underlying memory instance.