Skip to content

Document after() trace context behavior for Next.js #16815

@JPeer264

Description

@JPeer264

SDK

JavaScript SDK

Description

Add documentation explaining how to properly instrument deferred work scheduled with Next.js's after() function to maintain trace context.

Background

When using after() from next/server, spans created inside the deferred callback become detached root transactions instead of children of the request span. This happens because:

  1. The SDK flushes the request transaction when the response completes
  2. Deferred work in after() continues running afterward
  3. Spans created during deferred work have no in-memory parent to attach to

This results in dozens of small "db" or other transactions instead of one cohesive trace. See getsentry/sentry-javascript#19529 for the original issue and investigation.

Suggested Solution

Users should wrap their deferred work with startSpan inside the after() callback:

// ✓ Correct
after(
  Sentry.startSpan({ name: "background.task", op: "task" }, async () => {
    await doWork();
  })
);

// ✗ Wrong - task starts before after() runs
const task = doWork();
after(task);

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions