Skip to content

Commit e5a3885

Browse files
author
Luca Forstner
authored
fix: Memoize AsyncLocalStorage instance (#8831)
1 parent a6e2642 commit e5a3885

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

packages/nextjs/src/edge/asyncLocalStorageAsyncContextStrategy.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ interface AsyncLocalStorage<T> {
1111
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
1212
const MaybeGlobalAsyncLocalStorage = (GLOBAL_OBJ as any).AsyncLocalStorage;
1313

14+
let asyncStorage: AsyncLocalStorage<Hub>;
15+
1416
/**
1517
* Sets the async context strategy to use AsyncLocalStorage which should be available in the edge runtime.
1618
*/
@@ -23,7 +25,9 @@ export function setAsyncLocalStorageAsyncContextStrategy(): void {
2325
return;
2426
}
2527

26-
const asyncStorage: AsyncLocalStorage<Hub> = new MaybeGlobalAsyncLocalStorage();
28+
if (!asyncStorage) {
29+
asyncStorage = new MaybeGlobalAsyncLocalStorage();
30+
}
2731

2832
function getCurrentHub(): Hub | undefined {
2933
return asyncStorage.getStore();

packages/node/src/async/hooks.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,15 @@ type AsyncLocalStorageConstructor = { new <T>(): AsyncLocalStorage<T> };
1212
// AsyncLocalStorage only exists in async_hook after Node v12.17.0 or v13.10.0
1313
type NewerAsyncHooks = typeof async_hooks & { AsyncLocalStorage: AsyncLocalStorageConstructor };
1414

15+
let asyncStorage: AsyncLocalStorage<Hub>;
16+
1517
/**
1618
* Sets the async context strategy to use AsyncLocalStorage which requires Node v12.17.0 or v13.10.0.
1719
*/
1820
export function setHooksAsyncContextStrategy(): void {
19-
const asyncStorage = new (async_hooks as NewerAsyncHooks).AsyncLocalStorage<Hub>();
21+
if (!asyncStorage) {
22+
asyncStorage = new (async_hooks as NewerAsyncHooks).AsyncLocalStorage<Hub>();
23+
}
2024

2125
function getCurrentHub(): Hub | undefined {
2226
return asyncStorage.getStore();

0 commit comments

Comments
 (0)