Article

OpenTelemetry in a Turborepo monorepo: one shared package for all apps

Set up OpenTelemetry tracing once in a shared Turborepo package, use it in Next.js apps and Node.js services, and send traces over OTLP.

Published Updated 8 min read

A Turborepo monorepo often contains several Next.js apps and Node.js services, and if you copy the OpenTelemetry setup into each app, the copies become different over time.

This post puts the setup in one internal package, so that each app starts tracing with one import or one command-line flag. Traces go over OTLP to an OpenTelemetry Collector and from there to a vendor.

The code examples compile against pnpm 12, Turborepo 2.11, Next.js 16 and the OpenTelemetry JS SDK 0.301.

The shared telemetry package

Create a package in packages/telemetry with the name @repo/telemetry. This package owns all @opentelemetry/* dependencies, and the apps depend only on @repo/telemetry.

Use a compiled package

Turborepo documents just-in-time packages and compiled packages. A just-in-time package exports TypeScript source and works only when the consumer transpiles it, but a plain Node.js service has no bundler to do that. That is why you should use a compiled package that builds to dist with tsc.

Use this packages/telemetry/package.json:

{
  "name": "@repo/telemetry",
  "private": true,
  "type": "module",
  "exports": {
    ".": {
      "types": "./src/index.ts",
      "default": "./dist/index.js"
    },
    "./register": {
      "types": "./src/register.ts",
      "default": "./dist/register.js"
    }
  },
  "scripts": {
    "build": "tsc",
    "dev": "tsc --watch"
  },
  "dependencies": {
    "@opentelemetry/api": "catalog:",
    "@opentelemetry/auto-instrumentations-node": "catalog:",
    "@opentelemetry/instrumentation": "catalog:",
    "@opentelemetry/resources": "catalog:",
    "@opentelemetry/sdk-node": "catalog:",
    "@opentelemetry/semantic-conventions": "catalog:"
  }
}

The types condition points to the TypeScript source for editors and type checks, while the default condition points to the compiled JavaScript that Node.js and Next.js load. The Next.js apps do not need transpilePackages for this package.

The SDK setup

// packages/telemetry/src/index.ts
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import type { Instrumentation } from '@opentelemetry/instrumentation';
import { defaultResource, resourceFromAttributes } from '@opentelemetry/resources';
import { NodeSDK } from '@opentelemetry/sdk-node';
import {
  ATTR_DEPLOYMENT_ENVIRONMENT_NAME,
  ATTR_SERVICE_NAME,
  ATTR_SERVICE_VERSION,
} from '@opentelemetry/semantic-conventions';

export interface TelemetryOptions {
  // Fallback values. OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES override them.
  serviceName?: string;
  serviceVersion?: string;
  environment?: string;
  instrumentations?: Instrumentation[];
}

let sdk: NodeSDK | undefined;

export function startTelemetry(options: TelemetryOptions = {}): NodeSDK {
  if (sdk) return sdk;

  const attributes: Record<string, string> = {};
  if (options.serviceName) attributes[ATTR_SERVICE_NAME] = options.serviceName;
  if (options.serviceVersion) attributes[ATTR_SERVICE_VERSION] = options.serviceVersion;
  if (options.environment) attributes[ATTR_DEPLOYMENT_ENVIRONMENT_NAME] = options.environment;

  sdk = new NodeSDK({
    resource: defaultResource().merge(resourceFromAttributes(attributes)),
    instrumentations: options.instrumentations ?? [getNodeAutoInstrumentations()],
  });
  sdk.start();
  return sdk;
}

The code does not set an exporter or a sampler, because NodeSDK reads them from the standard OTEL_* environment variables. Without an explicit exporter, it creates an OTLP trace exporter and a batch span processor.

getNodeAutoInstrumentations() loads instrumentations for common Node.js libraries but skips the fs instrumentation by default. Use OTEL_NODE_ENABLED_INSTRUMENTATIONS or OTEL_NODE_DISABLED_INSTRUMENTATIONS to change the list per app. The values are names without the @opentelemetry/instrumentation- prefix, for example http,undici.

Resource attributes

Give every service these three resource attributes:

  • service.name
  • service.version
  • deployment.environment.name

The semantic conventions mark deployment.environment.name as stable and deprecate deployment.environment. Some vendor pages still show the old name, so check what your backend reads.

The code passes the fallback values as the resource option and the SDK merges the detected attributes on top, so OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES override the values in code. The SDK README recommends that you include defaultResource().

Do not use the serviceName option of NodeSDK for a fallback, because the SDK applies it after resource detection and it then overrides OTEL_SERVICE_NAME.

Next.js apps

Put instrumentation.ts in the app root or in src, and Next.js calls its register() function once when a server instance starts.

// apps/web/instrumentation.ts
export async function register() {
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    const { startTelemetry } = await import('@repo/telemetry');
    startTelemetry({ serviceName: 'web' });
  }
}

NodeSDK does not work in the Edge runtime, so the guard and the dynamic import() load the SDK only in the Node.js runtime, as the Next.js documentation shows.

Next.js already creates spans for requests, rendering and fetch calls, and the SDK exports these spans too. Set NEXT_OTEL_VERBOSE=1 to get more of them.

Fetch spans

The undici instrumentation also traces the global fetch API, so with both sources active, one outgoing fetch call produces two spans. Keep one source: set NEXT_OTEL_FETCH_DISABLED=1 to keep only the undici spans, or set OTEL_NODE_DISABLED_INSTRUMENTATIONS=undici to keep only the Next.js spans.

Bundled libraries

Next.js bundles the dependencies of Server Components and Route Handlers. Because an instrumentation can patch a library only when Node.js loads that library as a module, a library inside the Next.js bundle can end up producing no spans.

Add such a library to serverExternalPackages in next.config.ts, so that Next.js loads it with native require. The default list already contains packages such as pg, mongodb, @prisma/client and pino.

The @vercel/otel package

The Next.js documentation also offers @vercel/otel, which supports the Edge runtime. Version 2.3.0 declares peer ranges for the OpenTelemetry 2.x and 0.2xx lines, not 3.x and 0.301.x, so if you choose it, align the workspace versions with these ranges.

Plain Node.js services

A Node.js service must load the SDK before the application code, and the register entry does this.

// packages/telemetry/src/register.ts
import { startTelemetry } from './index.js';

const sdk = startTelemetry();

process.once('SIGTERM', () => {
  sdk.shutdown().finally(() => process.exit(0));
});

The SIGTERM handler shuts down the SDK before the process stops, which is the same pattern that the sdk-node README shows.

Load the entry with --import, as the OpenTelemetry getting-started guide also does for CommonJS apps. Without a loader hook, instrumentations only patch modules loaded with require(), so ESM apps also need --experimental-loader=@opentelemetry/instrumentation/hook.mjs.

Use this apps/api/package.json:

{
  "name": "api",
  "private": true,
  "type": "module",
  "scripts": {
    "build": "tsc",
    "start": "node --experimental-loader=@opentelemetry/instrumentation/hook.mjs --import @repo/telemetry/register dist/server.js"
  },
  "dependencies": {
    "@opentelemetry/instrumentation": "catalog:",
    "@repo/telemetry": "workspace:*"
  }
}

Node.js resolves the hook from the service folder, but by default pnpm links only direct dependencies into node_modules. The service therefore needs @opentelemetry/instrumentation as a direct dependency.

If you put the flags in NODE_OPTIONS, make sure that no other --require or --import flags conflict.

Turborepo configuration

Environment variables

Add this turbo.json in the repository root:

{
  "$schema": "https://turborepo.dev/schema.json",
  "tasks": {
    "build": {
      "dependsOn": ["^build"],
      "outputs": ["dist/**", ".next/**", "!.next/cache/**", "!.next/dev/**"]
    },
    "dev": {
      "dependsOn": ["^build"],
      "cache": false,
      "persistent": true,
      "passThroughEnv": ["OTEL_*", "NEXT_OTEL_*"]
    },
    "start": {
      "dependsOn": ["build"],
      "cache": false,
      "persistent": true,
      "passThroughEnv": ["OTEL_*", "NEXT_OTEL_*"]
    }
  }
}

Turborepo uses strict environment mode by default, where a task gets only the variables in env, globalEnv, passThroughEnv and globalPassThroughEnv, plus a built-in set such as PATH. Without passThroughEnv, turbo run dev removes all OTEL_* variables from the task.

Variables in env and globalEnv change the task hash, while variables in passThroughEnv reach the task without changing the hash. The SDK reads OTEL_* variables at runtime, so they do not change the build output and belong in passThroughEnv. If you put them in env, a new sampling rate causes a cache miss even though the output is identical.

Variables that Next.js inlines at build time change the output, so they belong in env, and Turborepo adds NEXT_PUBLIC_* automatically.

The configuration reference documents wildcards for env and globalEnv, and in Turborepo 2.11 the OTEL_* wildcard also works in passThroughEnv.

In production, set the same variables on the process that runs the app.

One version of each OpenTelemetry package

OpenTelemetry JS releases all stable packages with one version and all experimental packages with another, and the project README lists which versions work together.

The API package stores the active implementation on a global object, so a package that depends on an incompatible API version gets a no-op implementation and records no spans. The SDK packages also restrict the API version: @opentelemetry/sdk-node 0.301.2 requires @opentelemetry/api 1.10.x as a peer dependency.

Keep one version of each @opentelemetry/* package, and with pnpm 9.5 or later, use a catalog for that:

# pnpm-workspace.yaml
packages:
  - apps/*
  - packages/*

catalog:
  '@opentelemetry/api': 1.10.0
  '@opentelemetry/auto-instrumentations-node': 0.83.1
  '@opentelemetry/instrumentation': 0.301.2
  '@opentelemetry/resources': 3.1.1
  '@opentelemetry/sdk-node': 0.301.2
  '@opentelemetry/semantic-conventions': 1.45.0

The packages then use catalog: as the version, and the Turborepo documentation also lists syncpack, manypkg and sherif for this purpose.

Sending traces to a Collector

OTLP over HTTP or gRPC

The JavaScript SDK uses http/protobuf on port 4318 by default. For HTTP, the SDK adds /v1/traces to OTEL_EXPORTER_OTLP_ENDPOINT but uses OTEL_EXPORTER_OTLP_TRACES_ENDPOINT without changes. For gRPC, set OTEL_EXPORTER_OTLP_PROTOCOL=grpc and use port 4317.

NodeSDK also creates OTLP exporters for metrics and logs, because OTEL_METRICS_EXPORTER and OTEL_LOGS_EXPORTER both default to otlp. For a trace-only setup, set both to none.

# Runtime environment of the api service
export OTEL_SERVICE_NAME=api
export OTEL_RESOURCE_ATTRIBUTES=service.version=1.4.0,deployment.environment.name=production
export OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_TRACES_SAMPLER=parentbased_traceidratio
export OTEL_TRACES_SAMPLER_ARG=0.25
export OTEL_METRICS_EXPORTER=none
export OTEL_LOGS_EXPORTER=none

Collector configuration

# otel-collector.yaml
receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318

processors:
  memory_limiter:
    check_interval: 1s
    limit_mib: 400
    spike_limit_mib: 80

exporters:
  otlp_http:
    endpoint: ${env:OTLP_BACKEND_ENDPOINT}
    headers:
      Authorization: ${env:OTLP_BACKEND_AUTH}
    sending_queue:
      enabled: true
      batch:
        enabled: true

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [memory_limiter]
      exporters: [otlp_http]

The otlp receiver listens on port 4317 (gRPC) and port 4318 (HTTP). The Collector binds to localhost by default, while the value 0.0.0.0 also accepts connections from other containers.

The memory_limiter processor must be first in the pipeline. The otlp_http exporter adds /v1/traces to its endpoint, and its old name otlphttp is a deprecated alias. The ${env:...} syntax keeps the API key out of the file.

The configuration has no batch processor, because the OpenTelemetry project deprecated it in November 2026. Use exporter-level batching with sending_queue.batch.enabled: true instead, which becomes the default in v0.171.0, planned for February 2027. If you need batching in a processor, use the new queue_batch processor.

Check the file with otelcol validate --config=otel-collector.yaml before you deploy it.

Datadog and Grafana Cloud

Datadog accepts OTLP through the Datadog Agent, the DDOT Collector, an upstream OpenTelemetry Collector or a direct intake, and for production workloads it recommends an Agent or a Collector.

Grafana Cloud provides an OTLP endpoint, which it recommends for OpenTelemetry data, and for production Grafana recommends Grafana Alloy as the Collector.

The endpoint, header name and authentication differ per vendor, so copy them from the vendor documentation.

Sampling

The default sampler is parentbased_always_on, which keeps every trace. To keep only part of the traffic, set OTEL_TRACES_SAMPLER=parentbased_traceidratio and set OTEL_TRACES_SAMPLER_ARG to a probability between 0 and 1 (the default is 1.0).

The parent-based sampler applies the ratio only to root spans, and a child span follows the decision of its parent. Use the same sampler in every service, so that the first service decides and a trace across the web app and the api service stays complete.

The SDK reads these variables at runtime, so you can change the rate per environment without a new build.

To keep all traces with errors, you need tail sampling in the Collector, because head sampling cannot do that.

Checklist

  • @repo/telemetry is a compiled package and owns the SDK dependencies.
  • A catalog or a tool such as syncpack keeps one version of each @opentelemetry/* package.
  • Every service sets service.name, service.version and deployment.environment.name.
  • Next.js apps start the SDK in instrumentation.ts behind the NEXT_RUNTIME guard.
  • Each fetch call produces one span, not two.
  • Libraries that need instrumentation in Next.js are in serverExternalPackages.
  • Node.js services use --import, plus the loader hook for ESM.
  • turbo.json lists OTEL_* in passThroughEnv, not in env.
  • Metrics and logs exporters are none in a trace-only setup.
  • The Collector configuration passes otelcol validate and uses exporter-level batching.
  • Production uses parentbased_traceidratio with a known rate.

To have the tracing setup of your monorepo reviewed, see the frontend observability assessment or contact us.

Sources

Let's connect

Talk about your project

Tell us about your team and your problem. In 30 minutes we find out whether one of our offers fits, and if none does, we tell you.

Book a 30-minute call