Registry / aws / aws-xray-sdk-core

aws-xray-sdk-core

JSON →
library3.12.0jsnpmunverified

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.

npm install aws-xray-sdk-core
INSTALL
IMPORT
SIG · AWS-XRAY-SDK-CORE
A
aws-xray-sdk-core
awsjavascriptv3.12.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

AWSXRay
import AWSXRay from 'aws-xray-sdk-core';
const AWSXRay = require('aws-xray-sdk-core');
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.
Segment
import { Segment } from 'aws-xray-sdk-core';
import AWSXRay, { Segment } from 'aws-xray-sdk-core';
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.
Subsegment
import { Subsegment } from 'aws-xray-sdk-core';
Used for creating custom subsegments in manual tracing, or for type hinting in TypeScript. Often accessed via `AWSXRay.Subsegment` rather than direct import.
Logger
import type { Logger } from 'aws-xray-sdk-core/lib/types/logger';
For type-checking custom loggers when implementing a logger interface to pass to `AWSXRay.setLogger`.

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.

import AWSXRay from 'aws-xray-sdk-core'; import { RequestListener, createServer } from 'http'; // Configure X-Ray with a dummy daemon address for local testing if not running daemon // In a real environment, this would often be picked up from environment variables or default to localhost:2000 AWSXRay.setDaemonAddress('127.0.0.1:2000'); // Default is 127.0.0.1:2000 AWSXRay.setLogger(console); // Enable logging for demonstration AWSXRay.setSegmentName('MyNodeApp'); // Default segment name for incoming requests AWSXRay.captureHTTPsGlobal(require('http')); // Capture outgoing HTTP calls globally AWSXRay.captureHTTPsGlobal(require('https')); // Also for HTTPS // Enable automatic mode, which is default but good to be explicit for clarity AWSXRay.enableAutomaticMode(); // This requires 'cls-hooked' const requestListener: RequestListener = (req, res) => { // Get the current segment created by automatic mode const segment = AWSXRay.getSegment(); if (segment) { segment.addAnnotation('path', req.url || '/'); segment.addMetadata('requestMethod', req.method); AWSXRay.captureAsyncFunc('myCustomOperation', (subsegment) => { // Simulate some asynchronous work within a subsegment return new Promise(resolve => { setTimeout(() => { subsegment?.addAnnotation('status', 'success'); subsegment?.close(); // Always close subsegments res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello X-Ray Traced!'); resolve(true); }, 100); }); }, segment); // Pass segment explicitly to ensure it's linked } else { // Fallback if no segment is found (e.g., direct access without X-Ray context) console.warn('No active X-Ray segment found for this request.'); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello without X-Ray context!'); } }; const server = createServer(requestListener); const port = process.env.PORT || 3000; server.listen(port, () => { console.log(`Server running on http://localhost:${port}`); console.log('Try visiting http://localhost:3000'); }); // For a production setup, ensure the X-Ray daemon is running and accessible. // Remember to terminate your process cleanly in production, e.g., on SIGTERM.
Debug
Known issues
breakingNode.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.
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.
affects: >=3.0
gotchaAutomatic 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.
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.
affects: >=3.0
gotchaIf 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.
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.
affects: >=3.0
gotchaThe 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.
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.
affects: >=3.0
Errors
Common errors & fixes
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.
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.
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.
Error: Cannot find module 'cls-hooked'
The `cls-hooked` package, a direct dependency required for the SDK's automatic mode context propagation, is not installed or accessible.
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.
connect ECONNREFUSED 127.0.0.1:2000
The AWS X-Ray daemon is not running or is not accessible at the configured address and port (default: `127.0.0.1:2000`).
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.
Trace ID must be 35 hex characters
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.
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.
Upgrade
Version history
3.12.0latest on npm
Audit
Dependencies
cls-hookedrequiredRequired for automatic mode to propagate context across asynchronous operations.
aws-sdkoptionalRequired for `captureAWS` and `captureAWSClient` functionalities to instrument AWS SDK v2 calls. Version 2.7.15 or greater is recommended.
Agent activity
33 hits · last 30 days
node
30
OpenAI (training)
1
Resources