Overview
ESM (ECMAScript Modules) applications useimport statements rather than require(). Because dd-trace uses module load hooks to instrument third-party packages, ESM requires a different initialization approach from CommonJS.
Recommended: —import flag (Node.js 18.19+)
Pass--import dd-trace/register.js on the command line. This registers dd-trace’s ESM loader hook before any application modules are loaded:
register.js file calls node:module’s register() API to install loader-hook.mjs as a module customization hook:
register.js (dd-trace source)
Configuration with —import
Provide all configuration through environment variables when using--import dd-trace/register.js:
Programmatic configuration with —import
--import dd-trace/register.js reads configuration from environment variables only. For programmatic configuration alongside ESM, use the built-in dd-trace/initialize.mjs via --loader (which also self-registers the hook), or pass configuration through environment variables when using --import:
dd-trace/initialize.mjs module with --loader, which both registers the hook and initializes the tracer programmatically — but note --loader is deprecated as of Node.js 20:
package.json scripts
package.json
NODE_OPTIONS
Legacy: —loader flag
For Node.js versions before 18.19, use the--loader flag:
Mixed CJS/ESM projects
If your application mixes CommonJS and ESM (for example, a CommonJS server that imports ESM helpers), use--import dd-trace/register.js. The loader hook handles both module systems when registered via --import.
TypeScript ESM
For TypeScript projects compiled to ESM, use the same--import approach on the compiled output:
package.json
ts-node with ESM:
Verifying ESM instrumentation
Enable startup logs to confirm the loader hook was registered:Known limitations
- Some packages are excluded from ESM instrumentation by default:
import-in-the-middle,langsmith, certain OpenAI internal shims, and Anthropic SDK shims. - Packages that use private class fields or other features incompatible with module wrapping may not be instrumentable via ESM hooks.
- For bundled ESM output, see the Bundling guide.
