Next.js output: "standalone" shrinks production images by tracing only the files imported in your dependency graph. The catch is that APM tracers like dd-trace have to load before the app starts (via --require), so Next.js never sees them as imports and leaves them out of .next/standalone/node_modules.

Things that fall short in Next.js 14 standalone builds:

  • instrumentation.js alone: Does not load early enough for dd-trace to hook http and graphql cleanly.
  • serverExternalPackages: Not available in Next.js 14.x.
  • Phantom imports or manual node_modules copies: Either get stripped anyway or force you to maintain fragile transitive dependency copies.

Solution: global install in the base image + NODE_PATH

Install an exact pinned tracer version globally in your base image so it lives outside the traced app bundle:

# Dockerfile.base
RUN npm install -g dd-trace@5.87.0

In the runtime image, set NODE_PATH so Node resolves global modules and preload your config via NODE_OPTIONS:

# Dockerfile.app
ENV NODE_PATH=/usr/local/lib/node_modules
COPY next.config.js dd-trace.config.js ./
ENV NODE_OPTIONS="--require ./dd-trace.config"

dd-trace.config.js

// dd-trace.config.js
const tracer = require("dd-trace").init({
  logInjection: true,
  profiling: true,
  runtimeMetrics: true,
});

tracer.use("next");
tracer.use("graphql");
tracer.use("http", { blocklist: ["/api/health"] });

Keep global and lockfile versions in sync

Because local dev loads ./node_modules/dd-trace while production standalone containers load /usr/local/lib/node_modules/dd-trace, pin an exact version (no ^ or ~) across Dockerfile.base, package.json, and yarn.lock, and fail CI and postinstall if they drift.

To test locally instead of debugging inside CI pipelines, run the tracer agent container (gcr.io/datadoghq/agent:7) on your local compose network so you can verify spans, OTEL logs, and health-check blocklists before merging.