Skip to content

Node.js SDK

Instrument your Node.js applications to send traces and logs to Kopai.

Terminal window
npm install @opentelemetry/api @opentelemetry/sdk-node \
@opentelemetry/exporter-trace-otlp-http \
@opentelemetry/exporter-logs-otlp-http \
@opentelemetry/auto-instrumentations-node

Create a tracing.js file:

const { NodeSDK } = require("@opentelemetry/sdk-node");
const { OTLPTraceExporter } = require("@opentelemetry/exporter-trace-otlp-http");
const { getNodeAutoInstrumentations } = require("@opentelemetry/auto-instrumentations-node");
const sdk = new NodeSDK({
traceExporter: new OTLPTraceExporter({
url: "https://otlp.kopai.app/v1/traces",
headers: {
Authorization: `Bearer ${process.env.KOPAI_TOKEN}`,
},
}),
instrumentations: [getNodeAutoInstrumentations()],
});
sdk.start();
Terminal window
export KOPAI_TOKEN="your-token-here"
export OTEL_SERVICE_NAME="my-service"
node --require ./tracing.js app.js

The @opentelemetry/auto-instrumentations-node package provides automatic instrumentation for:

  • HTTP/HTTPS
  • Express, Fastify, Koa
  • MongoDB, PostgreSQL, MySQL
  • Redis, Memcached
  • gRPC
  • And more

For custom spans:

const { trace } = require("@opentelemetry/api");
const tracer = trace.getTracer("my-service");
async function processOrder(orderId) {
return tracer.startActiveSpan("processOrder", async (span) => {
span.setAttribute("order.id", orderId);
try {
// Your logic here
return result;
} finally {
span.end();
}
});
}