Skip to main content
The Tracer is the singleton exported by require('dd-trace'). It must be initialized before importing other libraries.
import tracer from 'dd-trace'

Methods

init(options?)

Initializes the tracer. This should be called before importing any other libraries to ensure all automatic instrumentation is set up correctly.
init(options?: TracerOptions): this
options
TracerOptions
Configuration options for the tracer. All options can also be set via environment variables.
returns
Tracer
The Tracer instance, for chaining.
const tracer = require('dd-trace').init({
  service: 'my-service',
  env: 'production',
  version: '1.0.0',
  logInjection: true,
})
init() must be called before importing any other modules. Calling it after importing instrumented libraries (e.g., express, pg) will result in incomplete tracing.

TracerOptions

OptionTypeDefaultEnv varDescription
servicestringinferred from package.jsonDD_SERVICEService name
envstring—DD_ENVEnvironment (e.g., prod, staging)
versionstringinferred from package.jsonDD_VERSIONApplication version
hostnamestring127.0.0.1DD_AGENT_HOSTTrace agent hostname
portnumber8126DD_TRACE_AGENT_PORTTrace agent port
urlstring—DD_TRACE_AGENT_URLTrace agent URL (takes priority over hostname/port)
sampleRatenumber—DD_TRACE_SAMPLE_RATEIngestion sample rate (0–1)
rateLimitnumber—DD_TRACE_RATE_LIMITGlobal rate limit for ingestion
logInjectionbooleanfalseDD_LOGS_INJECTIONInject trace IDs into log records
startupLogsbooleanfalseDD_TRACE_STARTUP_LOGSEmit startup diagnostic logs
profilingboolean—DD_PROFILING_ENABLEDEnable continuous profiling
runtimeMetricsbooleanfalseDD_RUNTIME_METRICS_ENABLEDEnable runtime metrics
pluginsbooleantrue—Load all built-in plugins
tagsobject—DD_TAGSGlobal tags applied to every span
logLevelstringdebugDD_TRACE_LOG_LEVELMinimum log level
dbmPropagationModestringdisabledDD_DBM_PROPAGATION_MODEDBM-to-APM link injection mode
dsmEnabledbooleanfalseDD_DATA_STREAMS_ENABLEDEnable Data Streams Monitoring
appsecboolean | object—DD_APPSEC_ENABLEDAppSec configuration
iastboolean | object—DD_IAST_ENABLEDIAST configuration
llmobsLLMObsEnableOptions—DD_LLMOBS_ENABLEDLLM Observability configuration

startSpan(name, options?)

Starts and returns a new Span representing a logical unit of work. The span is not automatically activated on the current scope — use trace() or scope().activate() for that.
startSpan(name: string, options?: SpanOptions): Span
name
string
required
The name of the operation.
options
SpanOptions
Options for the span.
returns
Span
A new Span object. Call span.finish() when the operation completes.
const span = tracer.startSpan('db.query', {
  childOf: parentSpan,
  tags: { 'db.type': 'postgresql' },
})

try {
  // perform operation
} finally {
  span.finish()
}

trace(name, fn) / trace(name, options, fn)

Instruments a function by automatically creating a span that is activated on the current scope. The span is finished automatically when the function returns.
trace<T>(name: string, fn: (span: Span) => T): T
trace<T>(name: string, fn: (span: Span, done: (error?: Error) => void) => T): T
trace<T>(name: string, options: TraceOptions & SpanOptions, fn: (span?: Span, done?: (error?: Error) => void) => T): T
name
string
required
The operation name.
options
TraceOptions & SpanOptions
Span and trace options.
fn
Function
required
The function to instrument. Receives the active span as the first argument. If the function accepts a second done callback parameter, the span is finished when done is called.
returns
T
The return value of fn.
The span is finished automatically when:
  • The function returns a non-promise value (synchronous)
  • The returned promise resolves or rejects
  • The done callback is called (when the function accepts two parameters)
// Synchronous
tracer.trace('compute', span => {
  span.setTag('key', 'value')
  // span finished when function returns
})

// Callback style
tracer.trace('web.request', (span, done) => {
  fetchData((err, data) => {
    done(err)
  })
})

// Promise
tracer.trace('web.request', () => {
  return fetch('/api/data')
})

// Async/await
async function handle() {
  return await tracer.trace('web.request', async () => {
    return await fetch('/api/data')
  })
}

// With options
tracer.trace('web.request', { resource: '/users', service: 'api', type: 'web' }, span => {
  // span has resource, service, and type set
})

wrap(name, fn) / wrap(name, options, fn)

Wraps a function so that tracer.trace() is called automatically every time the wrapped function is called.
wrap<T = (...args: any[]) => any>(name: string, fn: T): T
wrap<T = (...args: any[]) => any>(name: string, options: TraceOptions & SpanOptions, fn: T): T
wrap<T = (...args: any[]) => any>(name: string, options: (...args: any[]) => TraceOptions & SpanOptions, fn: T): T
name
string
required
The operation name.
options
TraceOptions & SpanOptions | Function
Static options object, or a function that receives the wrapped function’s arguments and returns options dynamically.
fn
Function
required
The function to wrap.
returns
T
A new function with the same signature as fn.
function handle() {
  // some code
}

const handleWithTrace = tracer.wrap('web.request', handle)

// With dynamic options
const wrappedFn = tracer.wrap(
  'db.query',
  (query) => ({ resource: query.table }),
  executeQuery
)
If the last argument of the wrapped function is a function (callback), the span finishes when that callback is called.

inject(spanContext, format, carrier)

Injects a SpanContext into a carrier object for cross-process propagation.
inject(spanContext: SpanContext | Span, format: string, carrier: any): void
spanContext
SpanContext | Span
required
The context to inject. A Span instance may be passed directly (its .context() will be used).
format
string
required
The carrier format. Common values: 'http_headers', 'text_map', 'binary'.
carrier
any
required
The carrier object to inject the context into (e.g., an HTTP headers object).
const headers = {}
tracer.inject(span.context(), 'http_headers', headers)
// headers now contains tracing propagation fields
fetch('/api/downstream', { headers })

extract(format, carrier)

Extracts a SpanContext from a carrier object.
extract(format: string, carrier: any): SpanContext | null
format
string
required
The carrier format (e.g., 'http_headers', 'text_map').
carrier
any
required
The carrier object to extract from (e.g., incoming request headers).
returns
SpanContext | null
The extracted SpanContext, or null if no context was found.
// In a server handler
app.get('/api', (req, res) => {
  const parentContext = tracer.extract('http_headers', req.headers)
  const span = tracer.startSpan('web.request', { childOf: parentContext })
  // ...
})

scope()

Returns a reference to the current Scope manager, used for manual context propagation.
scope(): Scope
returns
Scope
The active Scope manager.
const scope = tracer.scope()
const activeSpan = scope.active()

use(plugin, config)

Enables and optionally configures a built-in plugin.
use<P extends keyof Plugins>(plugin: P, config?: Plugins[P] | boolean): this
plugin
string
required
The name of the built-in plugin (e.g., 'express', 'pg', 'redis').
config
object | boolean
Plugin-specific configuration object, or false to disable the plugin.
returns
Tracer
The Tracer instance, for chaining.
const tracer = require('dd-trace').init()

tracer.use('pg', {
  service: 'pg-cluster',
})

tracer.use('express', {
  hooks: {
    request: (span, req, res) => {
      span.setTag('customer.id', req.query.id)
    },
  },
})

// Disable a plugin
tracer.use('fs', false)

setUser(user)

Links an authenticated user to the current trace.
setUser(user: User): Tracer
user
User
required
User properties. The id field is required.
returns
Tracer
The Tracer instance.
tracer.setUser({
  id: '123456789',         // required
  email: '[email protected]',
  name: 'Jane Doe',
  session_id: '987654321',
  role: 'admin',
  custom_field: 'value',   // arbitrary fields accepted
})

setUrl(url)

Sets the URL for the trace agent after initialization. Only use this when the URL cannot be set at init() time.
setUrl(url: string): this
url
string
required
The trace agent URL (e.g., 'http://localhost:8126').
returns
Tracer
The Tracer instance, for chaining.

getRumData()

Returns an HTML string containing <meta> tags for correlating the current server-side trace with a Real User Monitoring (RUM) view.
getRumData(): string
returns
string
HTML <meta> tag string to include in the document <head>.
Requires experimental.enableGetRumData: true in TracerOptions. The resulting HTML must not be cached, as the tags are time-sensitive and user-specific.
const tracer = require('dd-trace').init({
  experimental: { enableGetRumData: true },
})

// In a server-rendered page handler
res.send(`<html><head>${tracer.getRumData()}</head><body>...</body></html>`)

Properties

appsec

Access the Application Security Management (AppSec) SDK.
appsec: Appsec
See the AppSec API reference.

llmobs

Access the LLM Observability SDK.
llmobs: LLMObs
See the LLMObs API reference.

dogstatsd

Access the DogStatsD metrics client.
dogstatsd: DogStatsD
See the DogStatsD API reference.

dataStreamsCheckpointer

Access the Data Streams Monitoring manual checkpointer.
dataStreamsCheckpointer: DataStreamsCheckpointer
See the Data Streams API reference.

TracerProvider

OpenTelemetry-compatible TracerProvider constructor for registering dd-trace with @opentelemetry/api.
TracerProvider: opentelemetry.TracerProvider
See the OpenTelemetry Tracing reference.

aiguard

Access the AI Guard SDK for evaluating AI conversation safety.
aiguard: aiguard.AIGuard
const tracer = require('dd-trace').init({
  experimental: { aiguard: { enabled: true } }
})

const result = await tracer.aiguard.evaluate(messages, { block: false })
// result.action: 'ALLOW' | 'DENY' | 'ABORT'
Enable AI Guard by setting experimental.aiguard.enabled: true in TracerOptions or DD_AI_GUARD_ENABLED=true. This feature requires a connection to the AI Guard service via DD_AI_GUARD_ENDPOINT.

openfeature

OpenFeature-compatible provider for feature flag evaluation, backed by Datadog Remote Configuration.
openfeature: OpenFeatureProvider
This feature is in beta and requires experimental.flaggingProvider.enabled: true or DD_EXPERIMENTAL_FLAGGING_PROVIDER_ENABLED=true. Remote Configuration must be properly configured.

Baggage API

The following experimental methods manage W3C Baggage on the current async context. Baggage propagates across service boundaries as key-value pairs attached to the trace context.
These methods are experimental and subject to change.

setBaggageItem(key, value, metadata?)

Sets a baggage item on the current context.
setBaggageItem(key: string, value: string, metadata?: object): Record<string, string>
tracer.setBaggageItem('user.id', '123')
tracer.setBaggageItem('tenant', 'acme-corp')

getBaggageItem(key)

Returns a specific baggage item from the current context.
getBaggageItem(key: string): string | undefined
const userId = tracer.getBaggageItem('user.id')

getAllBaggageItems()

Returns all baggage items from the current context as a key-value record.
getAllBaggageItems(): Record<string, string>
const allBaggage = tracer.getAllBaggageItems()
// { 'user.id': '123', tenant: 'acme-corp' }

removeBaggageItem(key)

Removes a specific baggage item from the current context.
removeBaggageItem(key: string): Record<string, string>

removeAllBaggageItems()

Removes all baggage items from the current context.
removeAllBaggageItems(): Record<string, string>

Build docs developers (and LLMs) love