Requires Node.js >=22.15.0, OpenTelemetry API 1.10.x and SDK 3.x.
Use SDK-generation 0.300.x packages for experimental OpenTelemetry packages,
including sdk-node and instrumentation-http.
Usage
@fastify/otel works as a metric creator as well as application performance monitor for your Fastify application.
It must be configured before defining routes and other plugins in order to cover the most of your Fastify server.
It automatically wraps the main request handler by default; use instrumentHandler globally or per-route to disable its child span
Instruments all route hooks (defined at instance and route definition level) by default; use instrumentHooks globally or per-route to control auto-instrumented hook spans
onRequest
preParsing
preValidation
preHandler
preSerialization
onSend
onResponse
onError
Instruments automatically custom 404 Not Found handler
Example:
// ... in your OTEL setupconst FastifyOtelInstrumentation = require('@fastify/otel');// Service name comes from OpenTelemetry resources (via NodeSDK or OTEL_SERVICE_NAME)// as per https://opentelemetry.io/docs/languages/sdk-configuration/general/.const fastifyOtelInstrumentation = new FastifyOtelInstrumentation();fastifyOtelInstrumentation.setTracerProvider(provider)module.exports = { fastifyOtelInstrumentation }// ... in your Fastify definitionconst { fastifyOtelInstrumentation } = require('./otel.js');const Fastify = require('fastify');const app = fastify();// It is necessary to await for its register as it requires to be able// to intercept all route definitions
If the main request handler is not of the form (request, reply) (for example, @fastify/websocket
handlers take the form (socket, request)), the plugin attempts to find the Fastify request object
in any of the handler's arguments. If no request object can be found, instrumentation is skipped and
a debug level message is logged.
Registration using OpenTelemetry Node SDK
The plugin can be automatically registered using Node SDK, with registerOnInitialization option set to true.
// ... in your OTEL setupimport { NodeSDK } from '@opentelemetry/sdk-node';import FastifyOtelInstrumentation from "@fastify/otel";const sdk = new NodeSDK({ resource: ..., traceExporter: ..., instrumentations: [ ...others, new FastifyOtelInstrumentation({ registerOnInitialization: true }) ],});sdk.start();
Notes:
This instrumentation requires @opentelemetry/instrumentation-http to be able to propagate the traces all the way back to upstream
The HTTP instrumentation might cover all your routes although @fastify/otel just covers a subset of your application
For more information about OpenTelemetry, please refer to the OpenTelemetry JavaScript documentation.
APIs
FastifyOtelRequestContext
The FastifyOtelRequestContext is a wrapper around the OpenTelemetry Context and Tracer APIs. It also provides a way to manage the context of a request and its associated spans as well as some utilities to extract and inject further traces from and to the trace carrier.
FastifyOtelRequestContext#enabled: boolean
Whether OpenTelemetry is enabled for the instrumentation and route configuration.
FastifyOtelRequestContext#instrumented: boolean
Whether the current request has an OpenTelemetry span and context. This can be false
when instrumentation is enabled, but the request is intentionally skipped by options such
as ignorePaths. Use it as a runtime signal before using request span APIs.
FastifyOtelRequestContext#context: Context
The OpenTelemetry context object.
FastifyOtelRequestContext#tracer: Tracer
The OpenTelemetry tracer object.
FastifyOtelRequestContext#span: Span
The OpenTelemetry span object.
The span is created for each request and is automatically ended when the request is completed.
FastifyOtelRequestContext#inject: function
The OpenTelemetry inject function. It is used to inject the current context into a carrier object.
The carrier object can be any object that can hold key-value pairs, such as an HTTP request or response headers.
FastifyOtelRequestContext#extract: function
The OpenTelemetry extract function. It is used to extract a parent context from a carrier object.
The carrier object can be any object that can hold key-value pairs, such as an HTTP request or response headers.
The extracted context can be used as a parent span for a new span.
Whether to register the plugin on initialization. If set to true, the plugin will be registered automatically when the Fastify instance is created.
This is useful for applications that want to ensure that all routes are instrumented without having to manually register the plugin.
FastifyOtelInstrumentationOptions#ignorePaths: string | function
String or function to ignore paths from being instrumented.
If a string is provided, it will be used as a glob match pattern.
If a function is provided, it will be called with the request options and should return true if the path should be ignored.
FastifyOtelInstrumentationOptions#requestHook: function
A synchronous callback that runs immediately after the root request span is created.
span – the newly-created Span
info.request – the current FastifyRequest
Use it to add custom attributes, events, or rename the span.
If the function throws, the error is caught and logged so the request flow is never interrupted.
Examples
import { FastifyOtelInstrumentation } from '@fastify/otel';const fastifyOtelInstrumentation = new FastifyOtelInstrumentation({ registerOnInitialization: true, ignorePaths: (opts) => { // Ignore all paths that start with /ignore return opts.url.startsWith('/ignore'); },});// Service name should be set via environment variable:// export OTEL_SERVICE_NAME=my-server// or via NodeSDK resource configuration
const otel = new FastifyOtelInstrumentation({ requestHook: (span, request) => { // attach user info span.setAttribute('user.id', request.headers['x-user-id'] ?? 'anonymous') // optional: give the span a cleaner name span.updateName(`${request.method} ${request.routeOptions.url}`) }})
Control whether the Fastify route handler receives a child span. Defaults to true.
Set instrumentHandler: false globally to keep request spans without route handler child spans. A route can override the global setting with config.otel.instrumentHandler. Setting otel: false still disables all OpenTelemetry spans for the route.
FastifyOtelInstrumentationOptions#lifecycleHook: function
A synchronous callback that runs whenever a span is created for an instrumented Fastify lifecycle hook (route hooks, instance hooks, not-found handlers, and route handlers). It is not invoked when instrumentHooks skips a hook or instrumentHandler skips a route handler.
info.handler – the resolved handler or plugin name when available
info.request – the current FastifyRequest
Use it to rename hook spans or annotate them with framework-specific metadata (for example, tRPC procedure names) without registering additional Fastify hooks.
Control whether the instrumentation automatically calls span.recordException when a handler or hook throws.
Defaults to true, recording every exception. Set it to false if you prefer to record only the
exceptions that you consider actionable (for example to avoid noisy 4xx entries in Datadog Error Tracking).
When enabled, an exception thrown by an instrumented handler or hook is recorded once on the span where it
was thrown (for example the handler or hook span). The resulting request span is still marked as ERROR with
the error message, but the same propagated exception is not recorded again on it. Errors that never pass
through a wrapped handler or hook — such as reply.send(err) or done(err) — are recorded on the request
span. The duplicate-exception tracking is scoped per request.