The scope manager provides explicit control over which span is active in any given execution context. In most cases you do not need to use it directly—Documentation Index
Fetch the complete documentation index at: https://mintlify.com/datadog/dd-trace-js/llms.txt
Use this file to discover all available pages before exploring further.
tracer.trace() activates the span automatically. Use the scope manager only for advanced scenarios where the default async context propagation breaks down (e.g., custom timer queues, event emitters, or third-party async schedulers).
Access the scope manager via:
scope.active()
Returns the active Span in the current execution context, or null if there is none.
scope.activate(span, fn)
Activates a span for the duration of the provided function. All code executed synchronously or asynchronously from within fn—including setTimeout, setInterval, and promise continuations—will see span as the active span.
fn is forwarded as the return value of scope.activate().
scope.bind(target, [span])
Binds a function or promise to a specific span (or to the currently active span if no span is provided). The binding is permanent—the bound function always runs in the context of that span regardless of when or where it is called.
span argument | Result |
|---|---|
A Span instance | Function is always bound to that span. |
Omitted / undefined | Function is bound to the span active at the time bind() is called. |
null | Function is explicitly bound to no span. |
When to use the scope manager directly
Usescope.activate() or scope.bind() when:
- You maintain an internal queue of callbacks and execute them on a timer (the scope from when the callback was enqueued needs to be preserved).
- You use an event emitter whose listeners are called outside the original async context.
- You use a custom async scheduler that does not integrate with Node.js
AsyncLocalStorage.
tracer.trace() calls scope.activate() internally. If you use tracer.trace(), the span is already active for all code inside the callback—no additional scope management is needed.