Examples

Complete, runnable server examples for Express, Koa, Fastify, and NestJS with the Sophonz Node.js SDK — init-first ordering, request middleware, logging, and error handlers.

End-to-end entrypoints for the four supported frameworks, mirroring the official sophonz-express-server reference app. The most important rule is ordering: initialize the SDK before any instrumented module (express, koa, fastify, @nestjs/core, winston, ...) is loaded. Every example does this by calling init() at the top of the file and importing the app lazily via dynamic import() — so plain node main.js is enough and you never need a -r/preload file.

CAUTION — Initialize first

If an instrumented library is imported before init() runs, auto-instrumentation can miss it. Keep init() as the very first thing your process does, and load everything else afterward (dynamic import() inside bootstrap() is the simplest way to guarantee this).

Full server entrypoints

Pick your framework. Each tab is a complete main.ts you can run with node main.js (or bun main.js) — no preload flag.

// main.ts
import { enableDebugPayloadExporters, init } from '@sophonz/node-sdk';
 
// 1. Initialize the SDK before any instrumented module is loaded.
process.env.OTEL_EXPORTER_OTLP_ENDPOINT =
  process.env.OTEL_EXPORTER_OTLP_ENDPOINT ?? 'https://in.sophonz.ai';
process.env.OTEL_PROPAGATORS =
  process.env.OTEL_PROPAGATORS ?? 'tracecontext,baggage';
 
init({
  service: process.env.OTEL_SERVICE_NAME ?? 'sophonz-express-server',
  apiKey: process.env.SOPHONZ_API_KEY,
  consoleCapture: true,
  betaMode: true,
  advancedNetworkCapture: true,
  experimentalExceptionCapture: true,
});
 
if (process.env.SOPHONZ_DEBUG_PAYLOAD === 'true') {
  void enableDebugPayloadExporters();
}
 
// 2. Boot the app only after the SDK is initialized.
async function bootstrap(): Promise<void> {
  const { default: express } = await import('express');
  const { default: winston } = await import('winston');
  const {
    getWinstonTransport,
    setupExpressErrorHandler,
    sophonzExpressMiddleware,
  } = await import('@sophonz/node-sdk');
 
  const PORT = parseInt(process.env.PORT ?? '7788', 10);
 
  const logger = winston.createLogger({
    level: 'info',
    format: winston.format.json(),
    transports: [
      new winston.transports.Console(),
      getWinstonTransport('info', { detectResource: true }),
    ],
  });
 
  const app = express();
  app.use(express.json());
 
  // Enrich every request span with baggage, client IP, and user-agent.
  app.use(sophonzExpressMiddleware());
 
  app.get('/health', (_req, res) => {
    res.json({ status: 'ok', uptime: process.uptime() });
  });
 
  app.get('/api/users/:id', (req, res) => {
    logger.info('GET /api/users/:id', { id: req.params.id });
    res.json({ id: Number(req.params.id), name: 'Alice' });
  });
 
  app.get('/api/error', () => {
    throw new Error('Intentional error from /api/error');
  });
 
  // Records errors with status >= 500. Register after the routes.
  setupExpressErrorHandler(app);
 
  // Optional: your own fallback handler.
  app.use((err, _req, res, next) => {
    logger.error('Unhandled error', { message: err.message });
    if (res.headersSent) return next(err);
    res.status(500).json({ error: err.message });
  });
 
  app.listen(PORT, () => {
    logger.info(`listening on http://localhost:${PORT}`);
  });
}
 
void bootstrap();

Database query tracing

An example that extends query spans into the database. Apart from enabling SQLCommenter in init(), the application code is unchanged.

// main.ts
import { init } from '@sophonz/node-sdk';
 
init({
  service: 'checkout-api',
  apiKey: process.env.SOPHONZ_API_KEY,
  instrumentations: {
    // Append the W3C traceparent to every statement as a comment. The
    // pg_tracing extension in PostgreSQL reads it and emits plan spans under
    // the same trace. Without this the trace stops at the pg client.
    '@opentelemetry/instrumentation-pg': {
      addSqlCommenterCommentToQueries: true,
    },
  },
});
 
void bootstrap();
 
async function bootstrap() {
  const express = (await import('express')).default;
  const { Pool } = await import('pg');
 
  const pool = new Pool({ connectionString: process.env.DATABASE_URL });
  const app = express();
 
  app.get('/api/users/:id', async (req, res) => {
    // This query's span is a child of the request span, and thanks to the
    // comment the spans PostgreSQL produces join the same trace.
    const { rows } = await pool.query(
      'SELECT id, email FROM users WHERE id = $1',
      [req.params.id],
    );
    res.json(rows[0] ?? null);
  });
 
  app.listen(3000);
}

The trace a single request produces:

SpanDepthEmitted by
GET /api/users/:id1Express instrumentation
pg.query2pg instrumentation
Planner3pg_tracing
ExecutorRun3pg_tracing
SeqScan on users4pg_tracing

The last three appear only where the database has the pg_tracing extension installed. Without it the trace stops at pg.query, and the comment is still recorded in the database log. See Self-hosted PostgreSQL for installing the extension, or Cloud-managed PostgreSQL where it cannot be installed.

NOTE — Baggage propagation across services

With OTEL_PROPAGATORS=tracecontext,baggage, incoming baggage entries are copied onto the active span and the trace context by the middleware (prefixed baggage.). This is how caller-specific metadata — for example values set by the browser SDK — flows into your backend spans. service.name is a resource attribute fixed at startup, so each service keeps its own; traces are linked through the W3C traceparent header, not by sharing a service name.

See Middleware for the middleware, plugin, and interceptor options and Configuration for every init() setting.