javascript / expert
Snippet
WeakRef and FinalizationRegistry for In-Memory Next.js Cache Cleanup
Leveraging WeakRef and FinalizationRegistry creates garbage-collection-aware cache structures in Next.js dynamic runtime instances, automatically purging entries when memory pressure triggers object collection.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const cache = new Map();const registry = new FinalizationRegistry((key) => {cache.delete(key);});export function setWeakCache(key, value) {const ref = new WeakRef(value);cache.set(key, ref);registry.register(value, key);}export function getWeakCache(key) {const ref = cache.get(key);return ref ? ref.deref() ?? null : null;}
nextjs
Breakdown
1
const registry = new FinalizationRegistry((key) => {
Initializes a registry callback triggered asynchronously after registered target objects are garbage collected.
2
const ref = new WeakRef(value);
Creates a weak reference to the cached object without preventing engine garbage collection.
3
return ref ? ref.deref() ?? null : null;
Attempts to resolve the weakly held target reference using deref(), defaulting to null if collected.