Skip to content

Distributed tracing for Strapi 5 and Next.js

Connect Next.js and Strapi 5 with OpenTelemetry distributed tracing. Learn how to propagate trace context, instrument Koa and Knex, and isolate latency.

By the Revisionary team · · 5 min read

Yellow and green cables are neatly connected
Photo by Albert Stoynov on Unsplash

Distributed tracing across Next.js and Strapi 5 allows engineering teams to pinpoint latency spikes and network failures across the full request lifecycle. By propagating W3C Trace Context headers from Next.js server components down to Strapi's Koa engine and PostgreSQL or MySQL database queries, you can view the entire call graph in a single trace. This guide walks through setting up OpenTelemetry on both runtimes without modifying core application logic.

Why distributed tracing matters for headless stacks

When a page in Next.js renders slowly, the root cause could be slow React component rendering, network serialization, unoptimized Document Service queries in Strapi, or an unindexed database query. Standard application monitoring tools treat the front end and CMS as separate silos, leaving developers to correlate timestamps across multiple log aggregators.

Distributed tracing solves this by assigning a unique trace identifier to an incoming user request. As that request travels from the Next.js server runtime to the Strapi REST or GraphQL API and into the database via Knex, every service contributes child spans to the parent trace.

Using OpenTelemetry (OTel), the vendor-neutral standard for observability, ensures that your telemetry pipeline remains decoupled from specific monitoring providers such as Jaeger, Grafana Tempo, Datadog, or New Relic.

The trace propagation flow

Distributed tracing relies on standardized HTTP headers defined by the W3C Trace Context specification:

  1. A browser or client requests a page from Next.js.
  2. The Next.js OpenTelemetry instrumentation creates a root span and generates a traceparent header.
  3. Next.js server-side fetch calls to Strapi automatically inject the traceparent header.
  4. Strapi's HTTP server intercepts the header and continues the trace context.
  5. Strapi middlewares, controllers, and database drivers append nested child spans.
HeaderPurposeExample Value
traceparentIdentifies version, trace ID, parent span ID, and trace flags00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
tracestateCarries vendor-specific routing and filtering metadatacongo=t61rcWkgMzE,rojo=00f067a

Instrumenting Next.js with OpenTelemetry

Next.js provides native support for OpenTelemetry instrumentation via the instrumentation.ts file in the project root (or src/ directory).

1. Install dependencies

Install the required OpenTelemetry packages in your Next.js project:

bash
npm install @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/auto-instrumentations-node @opentelemetry/exporter-trace-otlp-proto

2. Configure the instrumentation file

Create instrumentation.ts in your Next.js application root:

typescript
export async function register() {
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    const { NodeSDK } = await import('@opentelemetry/sdk-node');
    const { getNodeAutoInstrumentations } = await import(
      '@opentelemetry/auto-instrumentations-node'
    );
    const { OTLPTraceExporter } = await import(
      '@opentelemetry/exporter-trace-otlp-proto'
    );

    const sdk = new NodeSDK({
      serviceName: 'nextjs-frontend',
      traceExporter: new OTLPTraceExporter({
        url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318/v1/traces',
      }),
      instrumentations: [
        getNodeAutoInstrumentations({
          // Disable fs instrumentation to keep span volume manageable
          '@opentelemetry/instrumentation-fs': { enabled: false },
        }),
      ],
    });

    sdk.start();
  }
}

When Next.js runs fetch() inside Server Components or Route Handlers, the Node.js HTTP instrumentation automatically injects the active trace context into outgoing HTTP requests.

Instrumenting Strapi 5 with OpenTelemetry

Strapi 5 runs on Node.js using Koa. Because tracing libraries need to hook into Node's core modules before other dependencies load, the cleanest approach is initializing OpenTelemetry via a preload script before Strapi bootstraps.

1. Install Strapi tracing packages

In your Strapi 5 project root, install the OpenTelemetry SDK and relevant instrumentations:

bash
npm install @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/auto-instrumentations-node @opentelemetry/exporter-trace-otlp-proto @opentelemetry/instrumentation-koa @opentelemetry/instrumentation-knex

2. Create the tracer initialization script

Create a file named tracer.js in the root of your Strapi project:

javascript
'use strict';

const { NodeSDK } = require('@opentelemetry/sdk-node');
const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');
const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-proto');
const { KoaInstrumentation } = require('@opentelemetry/instrumentation-koa');
const { KnexInstrumentation } = require('@opentelemetry/instrumentation-knex');

const traceExporter = new OTLPTraceExporter({
  url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318/v1/traces',
});

const sdk = new NodeSDK({
  serviceName: 'strapi-cms',
  traceExporter,
  instrumentations: [
    getNodeAutoInstrumentations({
      '@opentelemetry/instrumentation-fs': { enabled: false },
      '@opentelemetry/instrumentation-dns': { enabled: false },
    }),
    new KoaInstrumentation(),
    new KnexInstrumentation(),
  ],
});

sdk.start();

process.on('SIGTERM', () => {
  sdk.shutdown()
    .then(() => console.log('Tracing terminated'))
    .catch((error) => console.error('Error terminating tracing', error))
    .finally(() => process.exit(0));
});

3. Update the Strapi launch scripts

Preload tracer.js using Node's --require flag in package.json. This ensures that HTTP, Koa, and database libraries are patched before Strapi initializes:

json
{
  "scripts": {
    "develop": "node -r ./tracer.js ./node_modules/@strapi/strapi/bin/strapi.js develop",
    "start": "node -r ./tracer.js ./node_modules/@strapi/strapi/bin/strapi.js start"
  }
}
a blue background with lines and dots
Photo by Conny Schneider on Unsplash

Adding custom spans for Strapi Document Service operations

While automatic instrumentation captures all incoming HTTP requests and SQL queries, tracking custom business logic or specific Document Service queries helps make traces readable. You can explore how Strapi handles internal documents in our guide to the /blog/strapi-5-document-service-api-drafts-locales-and-queries.

To trace specific services or lifecycle hooks, create manual spans using @opentelemetry/api.

typescript
import { trace, SpanStatusCode } from '@opentelemetry/api';

const tracer = trace.getTracer('strapi-custom-logic');

export default {
  async findOneWithMetrics(documentId: string, locale?: string) {
    return tracer.startActiveSpan('documentService.findOne', async (span) => {
      span.setAttribute('strapi.document_id', documentId);
      if (locale) {
        span.setAttribute('strapi.locale', locale);
      }

      try {
        const result = await strapi.documents('api::article.article').findOne({
          documentId,
          locale,
        });

        span.setStatus({ code: SpanStatusCode.OK });
        return result;
      } catch (error) {
        span.recordException(error as Error);
        span.setStatus({
          code: SpanStatusCode.ERROR,
          message: (error as Error).message,
        });
        throw error;
      } finally {
        span.end();
      }
    });
  },
};

Correlating database queries with incoming requests

The KnexInstrumentation package automatically wraps database queries executed through Strapi's database layer. Each query span records:

  • db.system: The database engine (e.g., postgresql, mysql).
  • db.statement: The sanitized SQL query string.
  • Execution time and parameter placeholders.

When evaluating query performance, check the relationship between child database spans and parent Document Service operations. If an API request triggers dozens of identical SQL queries, you have an N+1 relation loading issue that should be resolved by optimizing your populate parameters.

For enterprise editorial setups managing extensive document revisions, query patterns in plugins can also be monitored. Systems like Revisionary, which provides content versioning and audit trails for Strapi 5 (as detailed in /docs/getting-started), run queries inside standard database transactions, making them fully traceable via the Knex instrumentation.

Local testing with OpenTelemetry Collector and Jaeger

To verify that traces propagate between Next.js and Strapi 5, you can run an OpenTelemetry Collector and Jaeger locally using Docker Compose.

1. Docker Compose configuration

Save the following docker-compose.telemetry.yml:

yaml
services:
  jaeger:
    image: jaegertracing/all-in-one:latest
    ports:
      - "16686:16686" # Jaeger Web UI
      - "4317:4317"   # OTLP gRPC receiver
      - "4318:4318"   # OTLP HTTP receiver
    environment:
      - COLLECTOR_OTLP_ENABLED=true

Start the collector with:

bash
docker compose -f docker-compose.telemetry.yml up -d

2. Verify trace context propagation

  1. Start both Strapi 5 and Next.js with OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318/v1/traces.
  2. Navigate to a page in your Next.js application that fetches content from Strapi.
  3. Open http://localhost:16686 in your browser.
  4. In the Search tab, select nextjs-frontend from the Service dropdown and click Find Traces.
  5. Select a trace. You should see a unified timeline that begins with the Next.js GET /page-route, branches into the outgoing fetch call, enters strapi-cms at the Koa router level, executes custom controllers, and terminates with the Knex database query spans.
code
[nextjs-frontend] GET /articles/hello-world (120ms)
  │
  └─ [nextjs-frontend] fetch GET http://cms:1337/api/articles (95ms)
       │
       └─ [strapi-cms] GET /api/articles (92ms)
            │
            ├─ [strapi-cms] documentService.findMany (78ms)
            │    │
            │    └─ [strapi-cms] knex:select from "articles" (12ms)
            │
            └─ [strapi-cms] koa.router (1ms)

Production considerations

Running tracing in production environments requires careful tuning to avoid overwhelming storage backends and degrading application throughput.

Sampling strategies

Tracing every single request is unnecessary and costly on high-traffic sites. Configure sampling at the SDK level using OpenTelemetry's built-in samplers:

  • ParentBasedSampler: Honors the sampling decision of the incoming request. If Next.js decided to sample the request, Strapi continues it. If Next.js dropped it, Strapi drops it as well.
  • TraceIdRatioBasedSampler: Samples a fixed percentage of total traffic (for instance, 5% or 10%).

Update tracer.js in Strapi to use a parent-based ratio sampler:

javascript
const { ParentBasedSampler, TraceIdRatioBasedSampler } = require('@opentelemetry/sdk-node');

const sdk = new NodeSDK({
  serviceName: 'strapi-cms',
  traceExporter,
  sampler: new ParentBasedSampler({
    root: new TraceIdRatioBasedSampler(0.1), // Sample 10% of unsampled root requests
  }),
  instrumentations: [/* ... */],
});

Security and data redaction

Tracing data can inadvertently capture sensitive information in HTTP headers or SQL query parameters. To maintain compliance and security:

  • Ensure authorization tokens (such as Authorization or strapi_jwt) are excluded from HTTP span attributes.
  • Use parameterized database queries so Knex spans record parameter markers ($1, $2) rather than raw credential strings or sensitive user inputs.
  • Ensure OTLP collector endpoints use mutual TLS or token authentication when transmitting telemetry across untrusted networks.

Summary

Implementing distributed tracing across Next.js and Strapi 5 replaces guesswork with actionable timing metrics. By preloading the OpenTelemetry SDK in Strapi, enabling Next.js instrumentation hooks, and letting W3C headers propagate across HTTP requests, engineering teams gain end-to-end visibility into backend bottlenecks, database serialization, and rendering latency.

TagsStrapi 5Next.jsOpenTelemetryObservabilityPerformanceNode.js

The Revisionary team

Developers who build Revisionary, a version history plugin for Strapi 5. We write about Strapi, web development, AI and application security.

This article was written with the help of AI.

All articles