@@ -10,10 +10,10 @@ const errorPages = new Set(['/404', '/500', '/_error', '/_not-found', '/_not-fou
1010
1111class NextPlugin extends ServerPlugin {
1212 static id = 'next'
13+ #requestsBySpanId = new WeakMap ( )
1314
1415 constructor ( ...args ) {
1516 super ( ...args )
16- this . _requestsBySpanId = new Map ( )
1717 this . addSub ( 'apm:next:page:load' , message => this . pageLoad ( message ) )
1818 }
1919
@@ -36,8 +36,8 @@ class NextPlugin extends ServerPlugin {
3636 analyticsSampler . sample ( span , this . config . measured , true )
3737
3838 // Store request by span ID to handle cases where child spans are activated
39- const spanId = span . context ( ) . toSpanId ( )
40- this . _requestsBySpanId . set ( spanId , req )
39+ const spanId = span . context ( ) . _spanId
40+ this . #requestsBySpanId . set ( spanId , req )
4141
4242 return { ...store , span }
4343 }
@@ -83,11 +83,6 @@ class NextPlugin extends ServerPlugin {
8383 this . config . hooks . request ( span , req , res )
8484
8585 span . finish ( )
86-
87- // Cleanup: Remove request from Map to prevent memory leaks
88- // since Map (unlike WeakMap) won't auto-garbage collect
89- const spanId = span . context ( ) . toSpanId ( )
90- this . _requestsBySpanId . delete ( spanId )
9186 }
9287
9388 pageLoad ( { page, isAppPath = false , isStatic = false } ) {
@@ -97,21 +92,12 @@ class NextPlugin extends ServerPlugin {
9792
9893 const span = store . span
9994
100- const spanId = span . context ( ) . toSpanId ( )
101-
102- // Convert parent ID from hex to decimal to match storage format.
103- let parentSpanId = null
104- if ( span . context ( ) . _parentId ) {
105- parentSpanId = span . context ( ) . _parentId . toString ( 10 )
106- }
95+ const spanId = span . context ( ) . _spanId
96+ const parentSpanId = span . context ( ) . _parentId
10797
10898 // Try current span first, then parent span.
10999 // This handles cases where pageLoad runs in a child span context
110- // (e.g., when OpenTelemetry TracerProvider creates "resolve page components" span)
111- let req = this . _requestsBySpanId . get ( spanId )
112- if ( ! req && parentSpanId ) {
113- req = this . _requestsBySpanId . get ( parentSpanId )
114- }
100+ const req = this . #requestsBySpanId. get ( spanId ) ?? this . #requestsBySpanId. get ( parentSpanId )
115101
116102 // safeguard against missing req in complicated timeout scenarios
117103 if ( ! req ) return
0 commit comments