From 53a0385b0370f5713acf6ff338716dbb665021a8 Mon Sep 17 00:00:00 2001 From: Luca Forstner Date: Thu, 17 Aug 2023 07:55:53 +0000 Subject: [PATCH] fix: Memoize `AsyncLocalStorage` instance --- .../src/edge/asyncLocalStorageAsyncContextStrategy.ts | 6 +++++- packages/node/src/async/hooks.ts | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/packages/nextjs/src/edge/asyncLocalStorageAsyncContextStrategy.ts b/packages/nextjs/src/edge/asyncLocalStorageAsyncContextStrategy.ts index e6872cd08893..36c6317248b4 100644 --- a/packages/nextjs/src/edge/asyncLocalStorageAsyncContextStrategy.ts +++ b/packages/nextjs/src/edge/asyncLocalStorageAsyncContextStrategy.ts @@ -11,6 +11,8 @@ interface AsyncLocalStorage { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any const MaybeGlobalAsyncLocalStorage = (GLOBAL_OBJ as any).AsyncLocalStorage; +let asyncStorage: AsyncLocalStorage; + /** * Sets the async context strategy to use AsyncLocalStorage which should be available in the edge runtime. */ @@ -23,7 +25,9 @@ export function setAsyncLocalStorageAsyncContextStrategy(): void { return; } - const asyncStorage: AsyncLocalStorage = new MaybeGlobalAsyncLocalStorage(); + if (!asyncStorage) { + asyncStorage = new MaybeGlobalAsyncLocalStorage(); + } function getCurrentHub(): Hub | undefined { return asyncStorage.getStore(); diff --git a/packages/node/src/async/hooks.ts b/packages/node/src/async/hooks.ts index c7e59de997ef..151b699c70d6 100644 --- a/packages/node/src/async/hooks.ts +++ b/packages/node/src/async/hooks.ts @@ -12,11 +12,15 @@ type AsyncLocalStorageConstructor = { new (): AsyncLocalStorage }; // AsyncLocalStorage only exists in async_hook after Node v12.17.0 or v13.10.0 type NewerAsyncHooks = typeof async_hooks & { AsyncLocalStorage: AsyncLocalStorageConstructor }; +let asyncStorage: AsyncLocalStorage; + /** * Sets the async context strategy to use AsyncLocalStorage which requires Node v12.17.0 or v13.10.0. */ export function setHooksAsyncContextStrategy(): void { - const asyncStorage = new (async_hooks as NewerAsyncHooks).AsyncLocalStorage(); + if (!asyncStorage) { + asyncStorage = new (async_hooks as NewerAsyncHooks).AsyncLocalStorage(); + } function getCurrentHub(): Hub | undefined { return asyncStorage.getStore();