{"id":12811,"library":"apollo-opentracing","title":"Apollo OpenTracing Plugin","description":"apollo-opentracing is a plugin designed to integrate OpenTracing-compatible distributed tracing with Apollo Server. It enables automatic tracing of GraphQL requests and individual field resolvers, providing insights into query performance, and allows for selective tracing of requests and fields. The library helps in debugging by logging queries and results and supports span context propagation via HTTP headers, crucial for connecting traces across services. As of version 3.0.45, released in March 2023, the project primarily receives maintenance updates, focusing on dependency compatibility. A key differentiator is its adherence to the OpenTracing standard, allowing integration with various tracing backends like Jaeger and Zipkin. However, it's important to note that OpenTracing itself has been superseded by OpenTelemetry, making this library focused on a legacy tracing standard.","status":"maintenance","version":"3.0.45","language":"javascript","source_language":"en","source_url":"https://github.com/DanielMSchmidt/apollo-opentracing","tags":["javascript","typescript"],"install":[{"cmd":"npm install apollo-opentracing","lang":"bash","label":"npm"},{"cmd":"yarn add apollo-opentracing","lang":"bash","label":"yarn"},{"cmd":"pnpm add apollo-opentracing","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core Apollo Server integration, required for the plugin system.","package":"apollo-server","optional":false},{"reason":"Environment utilities for Apollo Server. Specific version might depend on apollo-server.","package":"apollo-server-env","optional":false},{"reason":"GraphQL schema definition and execution, fundamental for any GraphQL server.","package":"graphql","optional":false},{"reason":"The core OpenTracing API, which this plugin implements.","package":"opentracing","optional":false}],"imports":[{"note":"The library exports its main plugin as a default export, requiring direct import or `.default` access in CommonJS.","wrong":"import { OpentracingPlugin } from 'apollo-opentracing';\nconst OpentracingPlugin = require('apollo-opentracing');","symbol":"OpentracingPlugin","correct":"import OpentracingPlugin from 'apollo-opentracing';"},{"note":"The plugin constructor requires 'server' and 'local' tracer instances, which are typically implementations of the OpenTracing `Tracer` interface.","wrong":"const plugin = OpentracingPlugin({});","symbol":"Tracing Options","correct":"import OpentracingPlugin from 'apollo-opentracing';\n\nconst plugin = OpentracingPlugin({\n  server: yourServerTracer,\n  local: yourLocalTracer,\n  shouldTraceRequest: (requestContext) => true,\n  shouldTraceFieldResolver: (source, args, context, info) => true\n});"}],"quickstart":{"code":"import { ApolloServer } from '@apollo/server';\nimport { startStandaloneServer } from '@apollo/server/standalone';\nimport { gql } from 'graphql-tag';\nimport OpentracingPlugin from 'apollo-opentracing';\nimport { MockTracer } from 'opentracing/lib/mock_tracer'; // Using a mock tracer for example\n\n// Initialize OpenTracing tracers\nconst serverTracer = new MockTracer();\nconst localTracer = new MockTracer();\n\n// Define your GraphQL schema\nconst typeDefs = gql`\n  type Book {\n    title: String\n    author: String\n  }\n\n  type Query {\n    books: [Book]\n    hello: String\n  }\n`;\n\n// Define your resolvers\nconst resolvers = {\n  Query: {\n    books: () => [\n      { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },\n      { title: 'To Kill a Mockingbird', author: 'Harper Lee' },\n    ],\n    hello: (parent, args, context, info) => {\n      // Access the current span from info.span if needed\n      if (info.span) {\n        info.span.log({ event: 'hello-resolver-executed' });\n      }\n      return 'Hello, GraphQL!';\n    },\n  },\n};\n\nasync function startApolloServer() {\n  const server = new ApolloServer({\n    typeDefs,\n    resolvers,\n    plugins: [\n      OpentracingPlugin({\n        server: serverTracer,\n        local: localTracer,\n        // Optional: conditionally trace requests\n        shouldTraceRequest: (requestContext) => {\n          return requestContext.request.operationName !== 'IntrospectionQuery';\n        },\n        // Optional: conditionally trace field resolvers\n        shouldTraceFieldResolver: (source, args, context, info) => {\n          return info.fieldName !== '__typename';\n        }\n      }),\n    ],\n  });\n\n  const { url } = await startStandaloneServer(server, {\n    listen: { port: 4000 },\n  });\n\n  console.log(`🚀 Server ready at ${url}`);\n  console.log('Perform a GraphQL query (e.g., query { books { title } }) and check tracer logs.');\n\n  // In a real application, you would export or periodically report spans from your tracer\n  // For MockTracer, you can access finished spans directly:\n  // console.log('Finished Spans:', serverTracer.finishedSpans());\n}\n\nstartApolloServer();","lang":"typescript","description":"This quickstart demonstrates setting up Apollo Server v3+ with `apollo-opentracing` using mock tracers. It initializes the Apollo Server with a basic schema and resolvers, then integrates the `OpentracingPlugin` to automatically trace requests and field resolutions. It also shows how to optionally control tracing and access the span within a resolver."},"warnings":[{"fix":"Migrate your Apollo Server setup to use the `ApolloServer` class and pass `OpentracingPlugin` within the `plugins` array in the constructor. Refer to Apollo Server v3+ documentation for correct initialization.","message":"The `apollo-opentracing` README examples show integration with `graphqlExpress` from `apollo-server-express`, which is part of Apollo Server v2 and earlier. However, the peer dependency is `apollo-server >=3.0.0`. Apollo Server v3+ requires a different setup using the `ApolloServer` class and its `plugins` array. The provided quickstart reflects the correct Apollo Server v3+ integration.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"For new projects, consider using OpenTelemetry directly with an instrumentation library like `@opentelemetry/instrumentation-graphql` instead of `apollo-opentracing`. For existing projects, evaluate migration paths from OpenTracing to OpenTelemetry.","message":"This library is built on OpenTracing, which has been officially deprecated since 2019 in favor of OpenTelemetry. While `apollo-opentracing` remains functional, new projects or those aiming for a future-proof observability stack should consider direct OpenTelemetry instrumentation for Apollo Server, which offers broader capabilities (metrics, logs, traces) and active development.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure you provide properly initialized instances of an `opentracing.Tracer` implementation (e.g., Jaeger, Zipkin, or a `MockTracer` for testing) for both the `server` and `local` options in the `OpentracingPlugin` constructor.","message":"The `OpentracingPlugin` requires two distinct `Tracer` instances: `server` (for the root span) and `local` (for all other spans). Incorrect or missing initialization of these tracers will lead to runtime errors or silent failures in tracing.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `OpentracingPlugin` is called with a configuration object containing `server` and `local` properties, each assigned a valid `opentracing.Tracer` instance: `plugins: [OpentracingPlugin({ server: myServerTracer, local: myLocalTracer })]`.","cause":"One or both of the required `server` or `local` OpenTracing `Tracer` instances were not provided or were `undefined` when initializing `OpentracingPlugin`.","error":"TypeError: Cannot read properties of undefined (reading 'startSpan')"},{"fix":"Ensure you are using `import OpentracingPlugin from 'apollo-opentracing';` (ESM) or `const OpentracingPlugin = require('apollo-opentracing').default;` (CJS) and then correctly invoking it as a function within the `plugins` array: `plugins: [OpentracingPlugin({ server: ..., local: ... })]`.","cause":"This error typically occurs when integrating `apollo-opentracing` with Apollo Server v3+ but using the older plugin registration method or an incorrect import, or if the plugin factory isn't called.","error":"Error: Apollo Server plugin must be an object with an 'requestDidStart' method or a function that returns such an object."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null}