{"id":15077,"library":"aws-xray-sdk-core","title":"AWS X-Ray SDK for Node.js Core","description":"The `aws-xray-sdk-core` package provides foundational capabilities for instrumenting Node.js applications to integrate with AWS X-Ray, enabling distributed tracing, performance analysis, and service map visualization. Currently at version 3.12.0, the SDK receives regular updates, typically on a monthly or bi-monthly release cadence, focusing on stability, bug fixes, and maintaining compatibility with AWS services. It supports both automatic and manual instrumentation modes; automatic mode, leveraging `cls-hooked` for asynchronous context propagation, is ideal for web frameworks like Express and Restify, as well as AWS Lambda functions, by automatically managing trace segments. Manual mode offers granular control over segment and subsegment creation for custom instrumentation scenarios. Its key differentiators include native integration with AWS services and robust support for Node.js environments.","status":"active","version":"3.12.0","language":"javascript","source_language":"en","source_url":"https://github.com/aws/aws-xray-sdk-node#master","tags":["javascript","amazon","api","aws","core","xray","x-ray","x ray","typescript"],"install":[{"cmd":"npm install aws-xray-sdk-core","lang":"bash","label":"npm"},{"cmd":"yarn add aws-xray-sdk-core","lang":"bash","label":"yarn"},{"cmd":"pnpm add aws-xray-sdk-core","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for automatic mode to propagate context across asynchronous operations.","package":"cls-hooked","optional":false},{"reason":"Required for `captureAWS` and `captureAWSClient` functionalities to instrument AWS SDK v2 calls. Version 2.7.15 or greater is recommended.","package":"aws-sdk","optional":true}],"imports":[{"note":"While `require` works in CJS contexts, ESM `import` is the idiomatic approach for modern Node.js development, especially with TypeScript, which this package ships types for.","wrong":"const AWSXRay = require('aws-xray-sdk-core');","symbol":"AWSXRay","correct":"import AWSXRay from 'aws-xray-sdk-core';"},{"note":"The `Segment` and `Subsegment` classes are typically imported as named exports when you need to interact with their constructors directly for manual mode or for type hinting in TypeScript. Otherwise, `AWSXRay.Segment` is available after importing the default export.","wrong":"import AWSXRay, { Segment } from 'aws-xray-sdk-core';","symbol":"Segment","correct":"import { Segment } from 'aws-xray-sdk-core';"},{"note":"Used for creating custom subsegments in manual tracing, or for type hinting in TypeScript. Often accessed via `AWSXRay.Subsegment` rather than direct import.","symbol":"Subsegment","correct":"import { Subsegment } from 'aws-xray-sdk-core';"},{"note":"For type-checking custom loggers when implementing a logger interface to pass to `AWSXRay.setLogger`.","symbol":"Logger","correct":"import type { Logger } from 'aws-xray-sdk-core/lib/types/logger';"}],"quickstart":{"code":"import AWSXRay from 'aws-xray-sdk-core';\nimport { RequestListener, createServer } from 'http';\n\n// Configure X-Ray with a dummy daemon address for local testing if not running daemon\n// In a real environment, this would often be picked up from environment variables or default to localhost:2000\nAWSXRay.setDaemonAddress('127.0.0.1:2000'); // Default is 127.0.0.1:2000\nAWSXRay.setLogger(console); // Enable logging for demonstration\nAWSXRay.setSegmentName('MyNodeApp'); // Default segment name for incoming requests\nAWSXRay.captureHTTPsGlobal(require('http')); // Capture outgoing HTTP calls globally\nAWSXRay.captureHTTPsGlobal(require('https')); // Also for HTTPS\n\n// Enable automatic mode, which is default but good to be explicit for clarity\nAWSXRay.enableAutomaticMode(); // This requires 'cls-hooked'\n\nconst requestListener: RequestListener = (req, res) => {\n  // Get the current segment created by automatic mode\n  const segment = AWSXRay.getSegment();\n\n  if (segment) {\n    segment.addAnnotation('path', req.url || '/');\n    segment.addMetadata('requestMethod', req.method);\n\n    AWSXRay.captureAsyncFunc('myCustomOperation', (subsegment) => {\n      // Simulate some asynchronous work within a subsegment\n      return new Promise(resolve => {\n        setTimeout(() => {\n          subsegment?.addAnnotation('status', 'success');\n          subsegment?.close(); // Always close subsegments\n          res.writeHead(200, { 'Content-Type': 'text/plain' });\n          res.end('Hello X-Ray Traced!');\n          resolve(true);\n        }, 100);\n      });\n    }, segment); // Pass segment explicitly to ensure it's linked\n  } else {\n    // Fallback if no segment is found (e.g., direct access without X-Ray context)\n    console.warn('No active X-Ray segment found for this request.');\n    res.writeHead(200, { 'Content-Type': 'text/plain' });\n    res.end('Hello without X-Ray context!');\n  }\n};\n\nconst server = createServer(requestListener);\nconst port = process.env.PORT || 3000;\n\nserver.listen(port, () => {\n  console.log(`Server running on http://localhost:${port}`);\n  console.log('Try visiting http://localhost:3000');\n});\n// For a production setup, ensure the X-Ray daemon is running and accessible.\n// Remember to terminate your process cleanly in production, e.g., on SIGTERM.\n","lang":"typescript","description":"Demonstrates basic setup of `aws-xray-sdk-core` in automatic mode, capturing an incoming HTTP request, adding annotations and metadata, and creating a custom subsegment for an asynchronous operation."},"warnings":[{"fix":"Upgrade your Node.js runtime to version 14.x or higher. If you need to support older Node.js versions, consider using a previous major version of the AWS X-Ray SDK for Node.js.","message":"Node.js 14.x or newer is required to use `aws-xray-sdk-core` version 3.x and above. Older Node.js runtimes are not supported.","severity":"breaking","affected_versions":">=3.0"},{"fix":"Ensure all asynchronous operations are wrapped with SDK provided functions like `AWSXRay.captureAsyncFunc`, `AWSXRay.capturePromise`, or are part of an automatically captured middleware context (e.g., Express middleware). Confirm `cls-hooked` is correctly installed.","message":"Automatic mode, which is the default, relies on the `cls-hooked` package for asynchronous context propagation. If context is lost during manual asynchronous operations (e.g., raw Promises or callbacks not wrapped by `captureAsyncFunc` or `capturePromise`), calls to `AWSXRay.getSegment()` or `AWSXRay.getSubsegment()` will return null.","severity":"gotcha","affected_versions":">=3.0"},{"fix":"Add `aws-sdk` to your project's dependencies: `npm install aws-sdk` or `yarn add aws-sdk`. This is separate from `@aws-sdk/client-*` packages for AWS SDK v3.","message":"If utilizing `captureAWS` or `captureAWSClient` to automatically instrument AWS SDK calls, a compatible version of the `aws-sdk` (v2.7.15 or greater) must be installed as a peer dependency in your project.","severity":"gotcha","affected_versions":">=3.0"},{"fix":"Consider setting `AWSXRay.setContextMissingStrategy('RUNTIME_ERROR')` or `process.env.AWS_XRAY_CONTEXT_MISSING = 'RUNTIME_ERROR'` during development to make missing trace contexts explicit and prevent silently untraced operations.","message":"The default behavior for a missing trace context (`AWS_XRAY_CONTEXT_MISSING`) is `LOG_ERROR`. This logs a warning but continues execution, potentially obscuring issues where tracing isn't properly initiated. For development, `RUNTIME_ERROR` can be more useful to immediately identify missing contexts.","severity":"gotcha","affected_versions":">=3.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Verify that `AWSXRay.enableAutomaticMode()` is called early in your application's lifecycle. Ensure the code executing is within a traced context (e.g., an incoming HTTP request handled by X-Ray middleware, or inside `captureAsyncFunc`). All async operations must properly propagate context for automatic mode to work reliably.","cause":"Attempting to retrieve the current segment or subsegment via `AWSXRay.getSegment()` or `AWSXRay.getSubsegment()` outside of an active trace context, or when automatic context propagation has failed.","error":"Failed to get the current sub/segment. Please ensure the AWS X-Ray SDK is running in automatic mode and that the context is available."},{"fix":"Install the `cls-hooked` dependency: `npm install cls-hooked` or `yarn add cls-hooked`. Although it's a direct dependency, issues can arise from aggressive dependency pruning or package manager inconsistencies.","cause":"The `cls-hooked` package, a direct dependency required for the SDK's automatic mode context propagation, is not installed or accessible.","error":"Error: Cannot find module 'cls-hooked'"},{"fix":"Ensure the X-Ray daemon is running and listening on the expected UDP port. Check the `AWS_XRAY_DAEMON_ADDRESS` environment variable or `AWSXRay.setDaemonAddress()` configuration if you've customized it. Verify local firewall rules are not blocking traffic to the daemon.","cause":"The AWS X-Ray daemon is not running or is not accessible at the configured address and port (default: `127.0.0.1:2000`).","error":"connect ECONNREFUSED 127.0.0.1:2000"},{"fix":"Inspect the incoming `X-Amzn-Trace-Id` header to ensure it conforms to the X-Ray trace header specification (`Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1`). This often indicates an issue upstream in the trace propagation chain.","cause":"The `X-Amzn-Trace-Id` HTTP header, which the SDK uses to propagate tracing context, is malformed or does not adhere to the expected format.","error":"Trace ID must be 35 hex characters"}],"ecosystem":"npm"}