{"library":"opentelemetry-instrumentation-fetch-node","title":"OpenTelemetry Node.js Fetch Instrumentation","description":"This package, `@gasbuddy/opentelemetry-instrumentation-fetch-node`, provides automatic OpenTelemetry instrumentation specifically for Node.js 18+ native `fetch` API calls. Unlike generic HTTP instrumentation, it is designed to work with the `undici`-based native `fetch` implementation in newer Node.js versions. The current stable version is 1.2.3, released in July 2024, with a consistent release cadence addressing bug fixes and features. A key differentiator is its use of Node.js's diagnostics channel for tracing and a unique workaround involving a 'phony fetch' to an unparseable URL, ensuring the instrumentation is active even with Node's lazy-loading behavior of the `fetch` API. It allows for advanced customization of spans and headers through an `onRequest` event. This is crucial for applications leveraging native `fetch` in modern Node environments that need comprehensive observability.","language":"javascript","status":"active","last_verified":"Sun Apr 19","install":{"commands":["npm install opentelemetry-instrumentation-fetch-node"],"cli":null},"imports":["import { NodeFetchInstrumentation } from '@gasbuddy/opentelemetry-instrumentation-fetch-node';","import type { NodeFetchInstrumentationConfig } from '@gasbuddy/opentelemetry-instrumentation-fetch-node';","import { registerInstrumentations } from '@opentelemetry/instrumentation';"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import { NodeSDK } from '@opentelemetry/sdk-node';\nimport { ConsoleSpanExporter } from '@opentelemetry/sdk-trace-node';\nimport { Resource } from '@opentelemetry/resources';\nimport { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';\nimport { registerInstrumentations } from '@opentelemetry/instrumentation';\nimport { NodeFetchInstrumentation } from '@gasbuddy/opentelemetry-instrumentation-fetch-node';\n\nconst sdk = new NodeSDK({\n  resource: new Resource({\n    [SemanticResourceAttributes.SERVICE_NAME]: 'my-fetch-service',\n  }),\n  traceExporter: new ConsoleSpanExporter(),\n});\n\n// Initialize and register the fetch instrumentation\nregisterInstrumentations([\n  new NodeFetchInstrumentation({\n    propagateContext: true, // Propagate trace context in outgoing headers\n    ignoreMethods: ['OPTIONS'], // Do not instrument OPTIONS requests\n    onRequest: (span, request) => {\n      // Add custom attributes to the span before the request is made\n      span.setAttribute('http.request.method', request.method);\n      span.setAttribute('http.request.headers.host', request.headers.get('host') ?? '');\n      // Example: Add a custom header to the outgoing request\n      // request.headers.set('x-custom-trace-id', span.spanContext().traceId);\n    },\n    applyCustomAttributesOnSpan: (span, request, response) => {\n        // Add custom attributes to the span after the response is received\n        if (response) {\n            span.setAttribute('http.response.status_code', response.status);\n            span.setAttribute('http.response.status_text', response.statusText);\n        }\n    }\n  }),\n]);\n\nsdk.start();\n\nasync function makeFetchRequest() {\n  try {\n    console.log('Making a fetch request...');\n    const response = await fetch('https://httpbin.org/get', {\n      method: 'GET',\n      headers: {\n        'Content-Type': 'application/json',\n        'Accept': 'application/json'\n      },\n    });\n    const data = await response.json();\n    console.log('Fetch request completed (URL):', data.url);\n  } catch (error) {\n    console.error('Fetch request failed:', error);\n  }\n}\n\n// Execute the request and then shut down the SDK gracefully\nmakeFetchRequest().finally(() => {\n  console.log('Shutting down OpenTelemetry SDK...');\n  // A small delay to ensure all spans are processed before shutdown\n  setTimeout(() => sdk.shutdown().then(() => console.log('SDK shutdown complete.')), 500);\n});","lang":"typescript","description":"Demonstrates how to set up and register `NodeFetchInstrumentation` with a basic OpenTelemetry Node SDK, make a traced native `fetch` request, and customize span attributes and request headers using `onRequest` and `applyCustomAttributesOnSpan` callbacks.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}