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
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:
- A browser or client requests a page from Next.js.
- The Next.js OpenTelemetry instrumentation creates a root span and generates a
traceparentheader. - Next.js server-side
fetchcalls to Strapi automatically inject thetraceparentheader. - Strapi's HTTP server intercepts the header and continues the trace context.
- Strapi middlewares, controllers, and database drivers append nested child spans.
| Header | Purpose | Example Value |
|---|---|---|
traceparent | Identifies version, trace ID, parent span ID, and trace flags | 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01 |
tracestate | Carries vendor-specific routing and filtering metadata | congo=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:
npm install @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/auto-instrumentations-node @opentelemetry/exporter-trace-otlp-proto2. Configure the instrumentation file
Create instrumentation.ts in your Next.js application root:
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:
npm install @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/auto-instrumentations-node @opentelemetry/exporter-trace-otlp-proto @opentelemetry/instrumentation-koa @opentelemetry/instrumentation-knex2. Create the tracer initialization script
Create a file named tracer.js in the root of your Strapi project:
'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:
{
"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"
}
}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.
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:
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=trueStart the collector with:
docker compose -f docker-compose.telemetry.yml up -d2. Verify trace context propagation
- Start both Strapi 5 and Next.js with
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318/v1/traces. - Navigate to a page in your Next.js application that fetches content from Strapi.
- Open
http://localhost:16686in your browser. - In the Search tab, select
nextjs-frontendfrom the Service dropdown and click Find Traces. - Select a trace. You should see a unified timeline that begins with the Next.js
GET /page-route, branches into the outgoingfetchcall, entersstrapi-cmsat the Koa router level, executes custom controllers, and terminates with the Knex database query spans.
[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:
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
Authorizationorstrapi_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.
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.