Skip to content
Projects
Groups
Snippets
Help
Loading...
Sign in
Toggle navigation
N
next.js
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Alex
next.js
Commits
d7b331f3
Unverified
Commit
d7b331f3
authored
Mar 03, 2026
by
Jiachi Liu
Committed by
GitHub
Mar 03, 2026
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
[otel] fix missing http.route attribute (#90832)
parent
296e1800
Hide whitespace changes
Inline
Side-by-side
Showing
14 changed files
with
332 additions
and
0 deletions
+332
-0
app-page.ts
packages/next/src/build/templates/app-page.ts
+8
-0
app-route.ts
packages/next/src/build/templates/app-route.ts
+8
-0
pages-api.ts
packages/next/src/build/templates/pages-api.ts
+8
-0
base-server.ts
packages/next/src/server/base-server.ts
+15
-0
pages-handler.ts
...ages/next/src/server/route-modules/pages/pages-handler.ts
+9
-0
page.tsx
.../app-dir/otel-parent-span-propagation/app/[slug]/page.tsx
+20
-0
layout.tsx
test/e2e/app-dir/otel-parent-span-propagation/app/layout.tsx
+8
-0
page.tsx
test/e2e/app-dir/otel-parent-span-propagation/app/page.tsx
+3
-0
collector.ts
test/e2e/app-dir/otel-parent-span-propagation/collector.ts
+62
-0
constants.ts
test/e2e/app-dir/otel-parent-span-propagation/constants.ts
+14
-0
instrumentation.ts
...e/app-dir/otel-parent-span-propagation/instrumentation.ts
+88
-0
next.config.js
test/e2e/app-dir/otel-parent-span-propagation/next.config.js
+6
-0
otel-parent-span-propagation.test.ts
...ent-span-propagation/otel-parent-span-propagation.test.ts
+73
-0
package.json
test/e2e/app-dir/otel-parent-span-propagation/package.json
+10
-0
No files found.
packages/next/src/build/templates/app-page.ts
View file @
d7b331f3
...
...
@@ -549,6 +549,7 @@ export async function handler(
interceptionRoutePatterns
)
res
.
setHeader
(
'Vary'
,
varyHeader
)
let
parentSpan
:
Span
|
undefined
const
invokeRouteModule
=
async
(
span
:
Span
|
undefined
,
context
:
AppPageRouteHandlerContext
...
...
@@ -592,6 +593,12 @@ export async function handler(
'next.span_name'
:
name
,
})
span
.
updateName
(
name
)
// Propagate http.route to the parent span if one exists (e.g.
// a platform-created HTTP span in adapter deployments).
if
(
parentSpan
&&
parentSpan
!==
span
)
{
parentSpan
.
setAttribute
(
'http.route'
,
route
)
}
}
else
{
span
.
updateName
(
`
${
method
}
${
srcPage
}
`
)
}
...
...
@@ -1597,6 +1604,7 @@ export async function handler(
if (isWrappedByNextServer && activeSpan) {
await handleResponse(activeSpan)
} else {
parentSpan = tracer.getActiveScopeSpan()
return await tracer.withPropagatedContext(
req.headers,
() =>
...
...
packages/next/src/build/templates/app-route.ts
View file @
d7b331f3
...
...
@@ -263,6 +263,7 @@ export async function handler(
)
try
{
let
parentSpan
:
Span
|
undefined
const
invokeRouteModule
=
async
(
span
?:
Span
)
=>
{
return
routeModule
.
handle
(
nextReq
,
context
).
finally
(()
=>
{
if
(
!
span
)
return
...
...
@@ -300,6 +301,12 @@ export async function handler(
'next.span_name'
:
name
,
})
span
.
updateName
(
name
)
// Propagate http.route to the parent span if one exists (e.g.
// a platform-created HTTP span in adapter deployments).
if
(
parentSpan
&&
parentSpan
!==
span
)
{
parentSpan
.
setAttribute
(
'http.route'
,
route
)
}
}
else
{
span
.
updateName
(
`
${
method
}
${
srcPage
}
`
)
}
...
...
@@ -497,6 +504,7 @@ export async function handler(
if (isWrappedByNextServer && activeSpan) {
await handleResponse(activeSpan)
} else {
parentSpan = tracer.getActiveScopeSpan()
await tracer.withPropagatedContext(
req.headers,
() =>
...
...
packages/next/src/build/templates/pages-api.ts
View file @
d7b331f3
...
...
@@ -86,6 +86,7 @@ export async function handler(
const
onRequestError
=
routeModule
.
instrumentationOnRequestError
.
bind
(
routeModule
)
let
parentSpan
:
Span
|
undefined
const
invokeRouteModule
=
async
(
span
?:
Span
)
=>
routeModule
.
render
(
req
,
res
,
{
...
...
@@ -147,6 +148,12 @@ export async function handler(
'next.span_name'
:
name
,
})
span
.
updateName
(
name
)
// Propagate http.route to the parent span if one exists (e.g.
// a platform-created HTTP span in adapter deployments).
if
(
parentSpan
&&
parentSpan
!==
span
)
{
parentSpan
.
setAttribute
(
'http.route'
,
route
)
}
}
else
{
span
.
updateName
(
`
${
method
}
${
srcPage
}
`
)
}
...
...
@@ -157,6 +164,7 @@ export async function handler(
if
(
isWrappedByNextServer
&&
activeSpan
)
{
await
invokeRouteModule
(
activeSpan
)
}
else
{
parentSpan
=
tracer
.
getActiveScopeSpan
()
await
tracer
.
withPropagatedContext
(
req
.
headers
,
()
=>
...
...
packages/next/src/server/base-server.ts
View file @
d7b331f3
...
...
@@ -876,6 +876,13 @@ export default abstract class Server<
const
tracer
=
getTracer
()
return
tracer
.
withPropagatedContext
(
req
.
headers
,
()
=>
{
// Capture the parent span before creating the handleRequest span.
// When deployed with an adapter, the platform's runtime may create its
// own OTEL HTTP server span before Next.js runs. We propagate http.route
// to this parent span so APM tools (e.g. Datadog) can derive the
// resource name correctly.
const
parentSpan
=
tracer
.
getActiveScopeSpan
()
return
tracer
.
trace
(
BaseServerSpan
.
handleRequest
,
{
...
...
@@ -934,6 +941,14 @@ export default abstract class Server<
'next.span_name'
:
name
,
})
span
.
updateName
(
name
)
// Propagate http.route to the parent span if one exists and
// is different from the handleRequest span. This ensures APM
// tools that read attributes from the outermost span (e.g.
// a platform-created HTTP span) can derive the resource name.
if
(
parentSpan
&&
parentSpan
!==
span
)
{
parentSpan
.
setAttribute
(
'http.route'
,
route
)
}
}
else
{
span
.
updateName
(
isRSCRequest
?
`RSC
${
method
}
`
:
`
${
method
}
`
)
}
...
...
packages/next/src/server/route-modules/pages/pages-handler.ts
View file @
d7b331f3
...
...
@@ -236,6 +236,7 @@ export const getHandler = ({
query: hasStaticProps ? {} : originalQuery,
})
let parentSpan: Span | undefined
const handleResponse = async (span?: Span) => {
const responseGenerator: ResponseGenerator = async ({
previousCacheEntry,
...
...
@@ -422,6 +423,13 @@ export const getHandler = ({
'next.span_name': name,
})
span.updateName(name)
// Propagate http.route to the parent span if one exists
// (e.g. a platform-created HTTP span in adapter
// deployments).
if (parentSpan && parentSpan !== span) {
parentSpan.setAttribute('http.route', route)
}
} else {
span.updateName(`
$
{
method
}
$
{
srcPage
}
`)
}
...
...
@@ -755,6 +763,7 @@ export const getHandler = ({
if (activeSpan) {
await handleResponse()
} else {
parentSpan = tracer.getActiveScopeSpan()
await tracer.withPropagatedContext(req.headers, () =>
tracer.trace(
BaseServerSpan.handleRequest,
...
...
test/e2e/app-dir/otel-parent-span-propagation/app/[slug]/page.tsx
0 → 100644
View file @
d7b331f3
import
{
Suspense
}
from
'react'
import
{
connection
}
from
'next/server'
async
function
SlugContent
({
params
}:
{
params
:
Promise
<
{
slug
:
string
}
>
})
{
await
connection
()
const
{
slug
}
=
await
params
return
<
p
>
slug:
{
slug
}
</
p
>
}
export
default
function
Page
({
params
,
}:
{
params
:
Promise
<
{
slug
:
string
}
>
})
{
return
(
<
Suspense
fallback=
{
<
p
>
loading...
</
p
>
}
>
<
SlugContent
params=
{
params
}
/>
</
Suspense
>
)
}
test/e2e/app-dir/otel-parent-span-propagation/app/layout.tsx
0 → 100644
View file @
d7b331f3
import
{
ReactNode
}
from
'react'
export
default
function
Root
({
children
}:
{
children
:
ReactNode
})
{
return
(
<
html
>
<
body
>
{
children
}
</
body
>
</
html
>
)
}
test/e2e/app-dir/otel-parent-span-propagation/app/page.tsx
0 → 100644
View file @
d7b331f3
export
default
function
Page
()
{
return
<
p
>
hello world
</
p
>
}
test/e2e/app-dir/otel-parent-span-propagation/collector.ts
0 → 100644
View file @
d7b331f3
import
{
Server
as
HttpServer
}
from
'node:http'
import
{
SavedSpan
}
from
'./constants'
export
interface
Collector
{
getSpans
:
()
=>
SavedSpan
[]
shutdown
:
()
=>
Promise
<
void
>
}
export
async
function
connectCollector
({
port
,
}:
{
port
:
number
}):
Promise
<
Collector
>
{
const
spans
:
SavedSpan
[]
=
[]
const
server
=
new
HttpServer
(
async
(
req
,
res
)
=>
{
if
(
req
.
method
!==
'POST'
)
{
res
.
writeHead
(
405
)
res
.
end
()
return
}
const
body
=
await
new
Promise
<
Buffer
>
((
resolve
,
reject
)
=>
{
const
acc
:
Buffer
[]
=
[]
req
.
on
(
'data'
,
(
chunk
:
Buffer
)
=>
{
acc
.
push
(
chunk
)
})
req
.
on
(
'end'
,
()
=>
{
resolve
(
Buffer
.
concat
(
acc
))
})
req
.
on
(
'error'
,
reject
)
})
const
newSpans
=
JSON
.
parse
(
body
.
toString
(
'utf-8'
))
as
SavedSpan
[]
spans
.
push
(...
newSpans
)
res
.
statusCode
=
202
res
.
end
()
})
await
new
Promise
<
void
>
((
resolve
,
reject
)
=>
{
server
.
listen
(
port
,
(
err
?:
Error
)
=>
{
if
(
err
)
{
reject
(
err
)
}
else
{
resolve
()
}
})
})
return
{
getSpans
()
{
return
spans
},
shutdown
()
{
return
new
Promise
<
void
>
((
resolve
,
reject
)
=>
server
.
close
((
err
)
=>
(
err
?
reject
(
err
)
:
resolve
()))
).
catch
((
err
)
=>
{
console
.
warn
(
'WARN: collector server disconnect failure:'
,
err
)
})
},
}
}
test/e2e/app-dir/otel-parent-span-propagation/constants.ts
0 → 100644
View file @
d7b331f3
import
{
SpanKind
}
from
'@opentelemetry/api'
export
type
SavedSpan
=
{
runtime
?:
string
traceId
?:
string
parentId
?:
string
name
?:
string
id
?:
string
kind
?:
SpanKind
timestamp
?:
number
duration
?:
number
attributes
?:
Record
<
string
,
any
>
status
?:
any
}
test/e2e/app-dir/otel-parent-span-propagation/instrumentation.ts
0 → 100644
View file @
d7b331f3
import
{
Resource
}
from
'@opentelemetry/resources'
import
{
SemanticResourceAttributes
}
from
'@opentelemetry/semantic-conventions'
import
{
SimpleSpanProcessor
,
SpanExporter
,
ReadableSpan
,
BasicTracerProvider
,
}
from
'@opentelemetry/sdk-trace-base'
import
{
AsyncLocalStorageContextManager
}
from
'@opentelemetry/context-async-hooks'
import
{
ExportResult
,
ExportResultCode
,
hrTimeToMicroseconds
,
}
from
'@opentelemetry/core'
import
{
SavedSpan
}
from
'./constants'
const
serializeSpan
=
(
span
:
ReadableSpan
):
SavedSpan
=>
({
runtime
:
process
.
env
.
NEXT_RUNTIME
,
traceId
:
span
.
spanContext
().
traceId
,
parentId
:
span
.
parentSpanId
,
name
:
span
.
name
,
id
:
span
.
spanContext
().
spanId
,
kind
:
span
.
kind
,
timestamp
:
hrTimeToMicroseconds
(
span
.
startTime
),
duration
:
hrTimeToMicroseconds
(
span
.
duration
),
attributes
:
span
.
attributes
,
status
:
span
.
status
,
})
class
TestExporter
implements
SpanExporter
{
constructor
(
private
port
:
number
)
{}
async
export
(
spans
:
ReadableSpan
[],
resultCallback
:
(
result
:
ExportResult
)
=>
void
)
{
try
{
const
response
=
await
fetch
(
`http://localhost:
${
this
.
port
}
`
,
{
method
:
'POST'
,
headers
:
{
'Content-Type'
:
'application/json'
,
},
body
:
JSON
.
stringify
(
spans
.
map
(
serializeSpan
)),
})
try
{
await
response
.
arrayBuffer
()
}
catch
(
e
)
{
// ignore.
}
if
(
response
.
status
>=
400
)
{
resultCallback
({
code
:
ExportResultCode
.
FAILED
,
error
:
new
Error
(
`http status
${
response
.
status
}
`
),
})
return
}
resultCallback
({
code
:
ExportResultCode
.
SUCCESS
})
}
catch
(
e
)
{
resultCallback
({
code
:
ExportResultCode
.
FAILED
,
error
:
e
})
}
}
shutdown
():
Promise
<
void
>
{
return
Promise
.
resolve
()
}
}
export
async
function
register
()
{
if
(
!
process
.
env
.
TEST_OTEL_COLLECTOR_PORT
)
{
throw
new
Error
(
'TEST_OTEL_COLLECTOR_PORT is not set'
)
}
const
port
=
parseInt
(
process
.
env
.
TEST_OTEL_COLLECTOR_PORT
)
const
contextManager
=
new
AsyncLocalStorageContextManager
()
contextManager
.
enable
()
const
provider
=
new
BasicTracerProvider
({
resource
:
new
Resource
({
[
SemanticResourceAttributes
.
SERVICE_NAME
]:
'test-next-app'
,
}),
})
provider
.
addSpanProcessor
(
new
SimpleSpanProcessor
(
new
TestExporter
(
port
)))
provider
.
register
({
contextManager
,
})
}
test/e2e/app-dir/otel-parent-span-propagation/next.config.js
0 → 100644
View file @
d7b331f3
/**
* @type {import('next').NextConfig}
*/
const
nextConfig
=
{}
module
.
exports
=
nextConfig
test/e2e/app-dir/otel-parent-span-propagation/otel-parent-span-propagation.test.ts
0 → 100644
View file @
d7b331f3
import
{
nextTestSetup
}
from
'e2e-utils'
import
{
retry
}
from
'next-test-utils'
import
{
type
Collector
,
connectCollector
}
from
'./collector'
const
COLLECTOR_PORT
=
9876
describe
(
'otel-parent-span-propagation'
,
()
=>
{
const
{
next
,
skipped
}
=
nextTestSetup
({
files
:
__dirname
,
skipDeployment
:
true
,
dependencies
:
require
(
'./package.json'
).
dependencies
,
env
:
{
TEST_OTEL_COLLECTOR_PORT
:
String
(
COLLECTOR_PORT
),
NEXT_TELEMETRY_DISABLED
:
'1'
,
},
})
if
(
skipped
)
{
return
}
let
collector
:
Collector
beforeEach
(
async
()
=>
{
collector
=
await
connectCollector
({
port
:
COLLECTOR_PORT
})
})
afterEach
(
async
()
=>
{
await
collector
.
shutdown
()
})
// Verifies that http.route is set on the handleRequest span.
// In production, when external OTEL instrumentation (e.g. Datadog,
// @opentelemetry/instrumentation-http) creates a parent HTTP server span,
// our fix also propagates http.route to that parent span so APM tools
// derive the resource name correctly (e.g. "GET /[slug]" instead of "GET").
// Parent span propagation is verified manually in production environments.
it
(
'should set http.route on handleRequest span for dynamic routes'
,
async
()
=>
{
await
next
.
fetch
(
'/test-slug'
)
await
retry
(
async
()
=>
{
const
spans
=
collector
.
getSpans
()
const
handleRequestSpan
=
spans
.
find
(
(
s
)
=>
s
.
attributes
?.[
'next.span_type'
]
===
'BaseServer.handleRequest'
&&
s
.
attributes
?.[
'http.target'
]
===
'/test-slug'
)
expect
(
handleRequestSpan
).
toBeDefined
()
expect
(
handleRequestSpan
!
.
attributes
?.[
'http.route'
]).
toBe
(
'/[slug]'
)
expect
(
handleRequestSpan
!
.
attributes
?.[
'next.route'
]).
toBe
(
'/[slug]'
)
expect
(
handleRequestSpan
!
.
name
).
toBe
(
'GET /[slug]'
)
})
})
it
(
'should set http.route on handleRequest span for static routes'
,
async
()
=>
{
await
next
.
fetch
(
'/'
)
await
retry
(
async
()
=>
{
const
spans
=
collector
.
getSpans
()
const
handleRequestSpan
=
spans
.
find
(
(
s
)
=>
s
.
attributes
?.[
'next.span_type'
]
===
'BaseServer.handleRequest'
&&
s
.
attributes
?.[
'http.target'
]
===
'/'
)
expect
(
handleRequestSpan
).
toBeDefined
()
expect
(
handleRequestSpan
!
.
attributes
?.[
'http.route'
]).
toBe
(
'/'
)
expect
(
handleRequestSpan
!
.
attributes
?.[
'next.route'
]).
toBe
(
'/'
)
expect
(
handleRequestSpan
!
.
name
).
toBe
(
'GET /'
)
})
})
})
test/e2e/app-dir/otel-parent-span-propagation/package.json
0 → 100644
View file @
d7b331f3
{
"dependencies"
:
{
"@opentelemetry/api"
:
"^1.7.0"
,
"@opentelemetry/context-async-hooks"
:
"^1.21.0"
,
"@opentelemetry/core"
:
"^1.21.0"
,
"@opentelemetry/resources"
:
"^1.21.0"
,
"@opentelemetry/sdk-trace-base"
:
"^1.21.0"
,
"@opentelemetry/semantic-conventions"
:
"^1.21.0"
}
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment