diff --git a/packages/next/src/server/next-server.ts b/packages/next/src/server/next-server.ts index f7cb690d004b4..cc24a570a85f0 100644 --- a/packages/next/src/server/next-server.ts +++ b/packages/next/src/server/next-server.ts @@ -156,6 +156,7 @@ export default class NextNodeServer extends BaseServer< protected middlewareManifestPath: string private _serverDistDir: string | undefined private imageResponseCache?: ResponseCache + private registeredInstrumentation: boolean = false protected renderWorkersPromises?: Promise protected dynamicRoutes?: { match: import('../shared/lib/router/utils/route-matcher').RouteMatchFn @@ -324,6 +325,8 @@ export default class NextNodeServer extends BaseServer< } protected async runInstrumentationHookIfAvailable() { + if (this.registeredInstrumentation) return + this.registeredInstrumentation = true await this.instrumentation?.register?.() } diff --git a/test/e2e/instrumentation-hook/register-once/instrumentation.js b/test/e2e/instrumentation-hook/register-once/instrumentation.js index f96e7a7d10a96..276640bdd6071 100644 --- a/test/e2e/instrumentation-hook/register-once/instrumentation.js +++ b/test/e2e/instrumentation-hook/register-once/instrumentation.js @@ -1,5 +1,11 @@ +let count = 0 + export function register() { if (process.env.NEXT_RUNTIME === 'nodejs') { + if (count > 0) { + throw new Error('duplicated-register') + } console.log('register-log') + count++ } } diff --git a/test/e2e/instrumentation-hook/register-once/register-once.test.ts b/test/e2e/instrumentation-hook/register-once/register-once.test.ts index 88bbb39ac7bb2..19b0ddb843787 100644 --- a/test/e2e/instrumentation-hook/register-once/register-once.test.ts +++ b/test/e2e/instrumentation-hook/register-once/register-once.test.ts @@ -14,4 +14,10 @@ describe('instrumentation-hook - register-once', () => { await next.fetch('/foo') expect(next.cliOutput).toIncludeRepeated('register-log', 1) }) + + it('should not error when concurrent requests are made', async () => { + await Promise.all([next.fetch('/foo'), next.fetch('/foo')]) + expect(next.cliOutput).toIncludeRepeated('register-log', 1) + expect(next.cliOutput).not.toInclude('duplicated-register') + }) })