Middleware

Enrich request spans in Express, Koa, Fastify, and NestJS with the Sophonz Node.js SDK — baggage, client IP, user-agent, custom attributes, and error handlers.

The SDK ships framework request middleware built on the API tools from the latest stable official @opentelemetry/api — middleware for Express and Koa, a plugin for Fastify, and an interceptor for NestJS. Each one copies OpenTelemetry baggage onto the active span, captures the client IP and user-agent, applies any custom attributes you provide, and forwards everything to the mutable trace context. Spans for all four frameworks are created automatically by the SDK's bundled auto-instrumentation; the middleware adds the request context on top.

Express

Register the middleware as early as possible in the chain so every downstream span inherits the attributes.

import express from 'express';
import { sophonzExpressMiddleware } from '@sophonz/node-sdk';
 
const app = express();
 
app.use(sophonzExpressMiddleware());
 
app.get('/', (req, res) => res.send('ok'));

With options:

app.use(
  sophonzExpressMiddleware({
    captureClientIp: true,
    captureUserAgent: true,
    captureBaggage: true,
    // static attributes added to every request
    attributes: { 'deployment.environment': process.env.NODE_ENV ?? 'dev' },
  }),
);

Per-request attributes via a function — it receives the Express req:

app.use(
  sophonzExpressMiddleware({
    attributes: (req) => ({
      'http.route': (req as express.Request).route?.path,
      'enduser.id': (req as express.Request).header('x-user-id') ?? '',
    }),
  }),
);

Koa

The Koa middleware is equivalent — register it before your routers.

import Koa from 'koa';
import { sophonzKoaMiddleware } from '@sophonz/node-sdk';
 
const app = new Koa();
 
app.use(sophonzKoaMiddleware());

With options (the attributes function receives the Koa ctx):

app.use(
  sophonzKoaMiddleware({
    captureClientIp: true,
    attributes: (ctx) => ({
      'http.route': (ctx as any).routePath,
      'enduser.id': (ctx as any).get('x-user-id') ?? '',
    }),
  }),
);

Fastify

The Fastify integration is a plugin that registers an onRequest hook. Register it once at the root, before your routes.

import Fastify from 'fastify';
import { sophonzFastifyPlugin } from '@sophonz/node-sdk';
 
const app = Fastify();
 
await app.register(sophonzFastifyPlugin());
 
app.get('/', async () => ({ status: 'ok' }));

With options (the attributes function receives the Fastify request):

await app.register(
  sophonzFastifyPlugin({
    captureClientIp: true,
    attributes: (req) => ({
      'enduser.id': (req as any).headers['x-user-id'] ?? '',
    }),
  }),
);

The plugin opts out of Fastify's encapsulation, so the hook applies to every route regardless of where you register it.

NestJS

The NestJS integration is a NestInterceptor. Register it globally — no Nest DI is required, just pass an instance. It works on both the Express and Fastify platform adapters.

import { NestFactory } from '@nestjs/core';
import { SophonzNestInterceptor } from '@sophonz/node-sdk';
import { AppModule } from './app.module';
 
const app = await NestFactory.create(AppModule);
 
app.useGlobalInterceptors(new SophonzNestInterceptor());
 
await app.listen(3000);

With options (the attributes function receives the underlying platform request):

app.useGlobalInterceptors(
  new SophonzNestInterceptor({
    attributes: (req) => ({
      'enduser.id': (req as any).headers['x-user-id'] ?? '',
    }),
  }),
);

A sophonzNestInterceptor(options?) factory is also exported if you prefer a function call over new.

NOTE — Initialize the SDK before loading the framework

The SDK must be initialized with init() before Express/Koa/Fastify/Nest are loaded so instrumentation can patch them. The simplest pattern is to call init() at the very top of your entrypoint and then load the rest of the app via dynamic import(). See the examples for full Express, Fastify, and NestJS entrypoints.

Options

sophonzExpressMiddleware, sophonzKoaMiddleware, sophonzFastifyPlugin, and SophonzNestInterceptor all accept the same SophonzMiddlewareOptions:

OptionTypeDefaultDescription
captureBaggagebooleantrueCopy every OTel baggage entry onto the span and mutable context, prefixed with baggage..
captureClientIpbooleantrueCapture the client IP as http.client.ip.
captureUserAgentbooleantrueCapture the user-agent header as http.user_agent.
attributesAttributes | ((reqOrCtx) => Attributes)—Extra attributes — a static object, or a function receiving the framework req/ctx.

NOTE — Telemetry never breaks requests

The middleware wraps its work in a try/catch. If attribute enrichment fails for any reason, the request continues normally and the error is swallowed — your request pipeline is never interrupted by telemetry.

Error handlers

When experimentalExceptionCapture is enabled (the default with init()), uncaught exceptions are captured automatically. To also record errors that your framework catches in its own error pipeline, register the matching error handler after your routes.

Express

import { setupExpressErrorHandler } from '@sophonz/node-sdk';
 
// ... app.use(routes) ...
 
setupExpressErrorHandler(app); // registers an Express error-handling middleware

By default it records errors whose status code is >= 500.

Koa

import { setupKoaErrorHandler } from '@sophonz/node-sdk';
 
setupKoaErrorHandler(app); // wraps the chain in try/catch and records thrown errors

Manual recording

Record a handled error anywhere with recordException:

import { recordException } from '@sophonz/node-sdk';
 
try {
  await doWork();
} catch (err) {
  await recordException(err, {
    attributes: { 'job.name': 'nightly-sync' },
  });
}

See the API Reference for the full signatures.