sentry-javascript icon indicating copy to clipboard operation
sentry-javascript copied to clipboard

Next.js 16 Turbopack: route handler spans lost via tRPC fetchRequestHandler — auto-wrapping needed

Open timothyclin opened this issue 6 months ago • 8 comments

Is there an existing issue for this?

  • [x] I have checked for existing issues https://github.com/getsentry/sentry-javascript/issues
  • [x] I have reviewed the documentation https://docs.sentry.io/
  • [x] I am using the latest SDK release https://github.com/getsentry/sentry-javascript/releases

How do you use Sentry?

Sentry Saas (sentry.io)

Which SDK are you using?

@sentry/nextjs

SDK Version

10.52.0

Framework Version

Next.js 16.2.4 (Turbopack), @sentry/nextjs 10.52.0, @trpc/server 11.17.0.

Link to Sentry event

https://t14c.sentry.io/explore/traces/trace/f6d797128c3e30fcdd8cd428d281f216/?end=2026-05-12T04%3A29%3A35&node=span-2b554e5309ada4c5&pageEnd=2026-05-12T04%3A29%3A35.000&pageStart=2026-05-09T04%3A29%3A35.000&project=-1&query=trace%3Af6d797128c3e30fcdd8cd428d281f216&search=project%3Ainspectionjarvis-dev&source=traces&start=2026-05-09T04%3A29%3A35&targetId=2b554e5309ada4c5&timestamp=1778430575

Reproduction Example/SDK Setup

Problem: Under Turbopack, withSentryConfig only injects values into the instrumentation file — it does not add a wrapping loader for route handlers (unlike the webpack path, which calls wrapRouteHandlerWithSentry via wrappingLoader.ts). Since tRPC's fetchRequestHandler introduces an async boundary that loses OpenTelemetry context, all child spans — whether manual (startSpan, startInactiveSpan) or via Sentry.trpcMiddleware — become orphaned. They never appear in Performance traces. What we see: every trace is middleware GET / middleware POST with no children. No visibility into procedure-level latency, file upload duration, or rules engine timing. What we tried (none work):

  1. Sentry.startSpan directly in exported route handler — compiled away by Turbopack
  2. Wrapper function around the handler — return types break Next.js route constraints
  3. Sentry.trpcMiddleware (from @sentry/node) — creates rpc.server spans but they never appear because no parent context exists
  4. NEXT_OTEL_VERBOSE=1 — Next.js emits more native spans but Sentry's handleOnSpanStart renames them all to middleware GET/POST What helps: Adding a Turbopack wrapping loader rule to constructTurbopackConfig.ts that mirrors what wrappingLoader.ts does for webpack, so route handlers maintain the Sentry scope chain across tRPC's async boundary. Alternatively, restoring the wrapRouteHandlerWithSentry wrapping through the Turbopack plugin system would fix this for all App Router users.

Steps to Reproduce

  1. Create Next.js 16 App Router project with Turbopack (default)
  2. Install @sentry/nextjs 10.52.0, @trpc/server 11.17.0
  3. Set up Sentry via instrumentation.ts + sentry.*.config.ts (standard manual setup)
  4. Create a tRPC router with a simple procedure that calls Sentry.startSpan
  5. Export GET/POST handlers using fetchRequestHandler
  6. npm run build && npm start
  7. Send a tRPC request
  8. Open Sentry Performance → traces

Expected Result

trace shows "tRPC handler" / "trpc/hello" with child spans

Actual Result

trace shows "middleware POST" with no children

Additional Context

No response

Priority

React with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding +1 or me too, to help us triage it.

timothyclin avatar May 10 '26 21:05 timothyclin

JS-2425

linear-code[bot] avatar May 10 '26 21:05 linear-code[bot]

One thing I want to separate out while we investigate: NEXT_OTEL_VERBOSE=1 causes Next.js to emit additional BaseServer/internal spans, and those can affect span descriptions as well as some of the span enrichment logic we apply on top of Next’s telemetry.

I’ll take a closer look, but it would be helpful to know:

  • How crucial is NEXT_OTEL_VERBOSE to reproducing this? does it happen if it is off?
  • Separate topic, which spans produced by the verbose flag there are you interested in?

logaretm avatar May 11 '26 20:05 logaretm

One thing I want to separate out while we investigate: NEXT_OTEL_VERBOSE=1 causes Next.js to emit additional BaseServer/internal spans, and those can affect span descriptions as well as some of the span enrichment logic we apply on top of Next’s telemetry.I’ll take a closer look, but it would be helpful to know:

* How crucial is `NEXT_OTEL_VERBOSE` to reproducing this? does it happen if it is off?

* Separate topic, which spans produced by the verbose flag there are you interested in?

NEXT_OTEL_VERBOSE is not crucial — we enabled it as a diagnostic to see if any spans would appear at all. The core issue reproduces without it: zero application-level spans (no tRPC procedures, no rules engine evaluation, no file upload spans) are visible under Turbopack, only middleware GET/POST root spans via handleOnSpanStart. We're not chasing any specific verbose spans — we just want proper child span visibility (tRPC, custom startSpan calls, etc.), regardless of whether the root span says middleware GET or GET /api/trpc/[trpc]. Let us know if you need a minimal reproduction repo. (Right now all we see is middleware POST/GET with no detailed information)

timothyclin avatar May 11 '26 20:05 timothyclin

Yea a minimal reproduction will be helpful to debug this faster. Thanks!

logaretm avatar May 11 '26 20:05 logaretm

sentryjs-20782

Minimal reproduction for getsentry/sentry-javascript#20782.

Issue

Under Turbopack (Next.js 16 default), child spans created via Sentry.startSpan inside tRPC procedures are lost. The outer Sentry.startSpan wrapping the route handler IS captured, but inner spans from the procedures never appear in the trace.

Repro steps

# 1. Clone
git clone https://github.com/timothyclin/sentryjs-20782.git
cd sentryjs-20782

2. Install

npm install

3. Configure Sentry

cp .env.sample .env.local

Edit .env.local — paste your NEXT_PUBLIC_SENTRY_DSN, SENTRY_AUTH_TOKEN, SENTRY_ORG, SENTRY_PROJECT

4. Production build + start (Turbopack is the default bundler)

npm run build npm start

5. Trigger tRPC calls (from another terminal)

for i in 1 2 3; do curl -s -X POST 'http://localhost:3000/api/trpc/hello'
-H 'Content-Type: application/json' -d '{}' > /dev/null done

6. Check Sentry

Go to sentry.io > Explore > your 20782-b3 project

Search for transactions (event.type:transaction)

Expected vs Actual

Expected: Each trace shows the outer tRPC handler span with a child trpc/hello or trpc/slowQuery span inside it:

span parent description op
✅ — tRPC handler http.server
❌ tRPC handler trpc/hello handler

Key detail

  1. GET/POST handlers are wrapped in Sentry.startSpan({ name: "tRPC handler", op: "http.server" }) — this outer span IS created and visible.

  2. Each procedure also calls Sentry.startSpan({ name: "trpc/hello" / "trpc/slowQuery", op: "handler" }) — these are NEVER created as children.

  3. fetchRequestHandler introduces an async boundary that loses OpenTelemetry context under Turbopack.

Verification with Sentry API

TOKEN="your-sentry-auth-token"
ORG="t14c"
PROJECT_ID="your-numeric-project-id"

List transactions — they exist

curl -s -H "Authorization: Bearer $TOKEN"
"https://sentry.io/api/0/organizations/$ORG/events/?project=$PROJECT_ID&field=id&field=transaction&field=title&field=timestamp&sort=-timestamp&limit=5" | jq .

Get spans for a specific event — 0 child spans

EVENT_ID="..." curl -s -H "Authorization: Bearer $TOKEN"
"https://sentry.io/api/0/projects/$ORG/your-project-slug/events/$EVENT_ID/" | jq '.spans'

# sentryjs-20782

Minimal reproduction for [getsentry/sentry-javascript#20782](https://github.com/getsentry/sentry-javascript/issues/20782).

Issue

Under Turbopack (Next.js 16 default), child spans created via Sentry.startSpan inside tRPC procedures are lost. The outer Sentry.startSpan wrapping the route handler IS captured, but inner spans from the procedures never appear in the trace.

Repro steps

# 1. Clone
git clone https://github.com/timothyclin/sentryjs-20782.git
cd sentryjs-20782

# 2. Install
npm install

# 3. Configure Sentry
cp .env.sample .env.local
# Edit .env.local — paste your NEXT_PUBLIC_SENTRY_DSN, SENTRY_AUTH_TOKEN, SENTRY_ORG, SENTRY_PROJECT

# 4. Production build + start (Turbopack is the default bundler)
npm run build
npm start

# 5. Trigger tRPC calls (from another terminal)
for i in 1 2 3; do
  curl -s -X POST 'http://localhost:3000/api/trpc/hello' \
    -H 'Content-Type: application/json' -d '{}' > /dev/null
done

# 6. Check Sentry
# Go to sentry.io > Explore > your 20782-b3 project
# Search for transactions (event.type:transaction)

Expected vs Actual

Expected: Each trace shows the outer tRPC handler span with a child trpc/hello or trpc/slowQuery span inside it:

span parent description op
✅ — tRPC handler http.server
❌ tRPC handler trpc/hello handler

Actual: Only the outer span appears. No child spans are recorded:

span parent description op
✅ — tRPC handler http.server
❌ — — —

The POST /api/trpc/[trpc] transactions exist in the project (Sentry API confirms them), and the span.description for the root span is tRPC handler — so the outer wrapping works. But the inner child spans (trpc/hello, trpc/slowQuery) never materialize because fetchRequestHandler introduces an async boundary that loses the OpenTelemetry context under Turbopack.

What's in the repro

File Purpose
instrumentation.ts Standard @sentry/nextjs registration
sentry.server.config.ts Server-side Sentry init (DSN, tracesSampleRate=1.0)
sentry.client.config.ts Client-side init
sentry.edge.config.ts Edge runtime init
next.config.ts withSentryConfig wrapper
src/server/trpc/root.ts tRPC router with 2 procedures, each calling Sentry.startSpan
src/app/api/trpc/[trpc]/route.ts Route handler using fetchRequestHandler, wrapped in Sentry.startSpan
src/app/page.tsx Client page with buttons to trigger each procedure

Versions

Package Version
next 16.2.4
@sentry/nextjs 10.52.0
@trpc/server 11.13.0
react 19.2.4

Key detail

  1. GET/POST handlers are wrapped in Sentry.startSpan({ name: "tRPC handler", op: "http.server" }) — this outer span IS created and visible.
  2. Each procedure also calls Sentry.startSpan({ name: "trpc/hello" / "trpc/slowQuery", op: "handler" }) — these are NEVER created as children.
  3. fetchRequestHandler introduces an async boundary that loses OpenTelemetry context under Turbopack.

Verification with Sentry API

TOKEN="your-sentry-auth-token"
ORG="t14c"
PROJECT_ID="your-numeric-project-id"

# List transactions — they exist
curl -s -H "Authorization: Bearer $TOKEN" \
  "https://sentry.io/api/0/organizations/$ORG/events/?project=$PROJECT_ID&field=id&field=transaction&field=title&field=timestamp&sort=-timestamp&limit=5" | jq .

# Get spans for a specific event — 0 child spans
EVENT_ID="..."
curl -s -H "Authorization: Bearer $TOKEN" \
  "https://sentry.io/api/0/projects/$ORG/your-project-slug/events/$EVENT_ID/" | jq '.spans'

timothyclin avatar May 12 '26 14:05 timothyclin

Yea a minimal reproduction will be helpful to debug this faster. Thanks!

responded - please check repo https://github.com/timothyclin/sentryjs-20782

timothyclin avatar May 12 '26 14:05 timothyclin

I tested out the repro, works as expected

CleanShot 2026-05-12 at 15.53.59@2x.png

If you can reproduce this locally, try turning on debug: true in the sentry init options and send us the logs you get.

Sentry.init({
  dsn: process.env.SENTRY_DSN || process.env.NEXT_PUBLIC_SENTRY_DSN,
  tracesSampleRate: 1.0,

 // add those for more logs and details about what is getting sent to sentry
  debug: true,
  beforeSendTransaction(event) {
    console.log(
      "[sentry transaction]",
      event.transaction,
      (event.spans || []).map(span => ({
        description: span.description,
        op: span.op,
        parent_span_id: span.parent_span_id,
        span_id: span.span_id,
      })),
    );

    return event;
  },
});

logaretm avatar May 12 '26 19:05 logaretm

We did some more debugging and realized that the issue was neither Sentry SDK nor Turbopack but a combination of the following: 1. SDK setup was partially done 2. missing await on Sentry.startSpan() in the handler, and 3. missing broserTracingIntegration which breaks distributed tracing headers which made some transactions 'orphan' and showing up without parents. Thanks for your speedy feedback!

timothyclin avatar May 12 '26 21:05 timothyclin