AWS X-Ray SDK for Node.js Core

3.12.0 · active · verified Tue Apr 21

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

view raw JSON →