AWS X-Ray SDK for Koa
raw JSON → 3.12.0 verified Sat Apr 25 auth: no javascript
Official AWS X-Ray middleware for Koa 2.x that records incoming/outgoing requests and responses. Version 3.12.0 is latest stable; released with the aws-xray-sdk-node monorepo on a monthly cadence. Key differentiator: deep AWS service integration with automatic segment/subsegment management via cls-hooked. Supports ESM and CJS; ships TypeScript types. Requires aws-xray-sdk-core and Koa 2.x. Offers both automatic (default) and manual tracing modes. Minimal overhead but can cause context issues if middleware order is wrong.
Common errors
error TypeError: Cannot read properties of undefined (reading 'getSegment') ↓
cause AWSXRay is not imported or core SDK not initialized.
fix
Ensure aws-xray-sdk-core is installed and imported: import AWSXRay from 'aws-xray-sdk-core'.
error Error: No segment open, cannot add subsegment ↓
cause Middleware not applied before route handler, or context lost in async code.
fix
Add app.use(openSegment('name')) before routes; use manual mode if async context is lost.
error AssertionError [ERR_ASSERTION]: The 'name' argument must be of type string ↓
cause openSegment called without a segment name argument.
fix
Provide a name string: app.use(openSegment('myApp')).
Warnings
gotcha openSegment middleware must be the last middleware before route definitions in automatic mode, otherwise cls-hooked context may be lost. ↓
fix Place app.use(openSegment(...)) immediately before your router or route middleware.
deprecated Version 3.7.0 is deprecated; upgrade to latest. ↓
fix Update to >=3.8.0, preferably 3.12.0.
breaking CLS context may not work with async/await if not placed correctly; manual mode is safer for complex async flows. ↓
fix Use manual mode with ctx.segment if you encounter context loss.
gotcha Segment must be closed manually in some cases; openSegment automatically closes on response but subsegments need explicit close. ↓
fix Use AWSXRay.getSegment()?.close() or let the SDK handle it via automatic mode.
Install
npm install aws-xray-sdk-koa2 yarn add aws-xray-sdk-koa2 pnpm add aws-xray-sdk-koa2 Imports
- xrayKoa wrong
const xrayKoa = require('aws-xray-sdk-koa2')correctimport { xrayKoa } from 'aws-xray-sdk-koa2' - openSegment wrong
const openSegment = require('aws-xray-sdk-koa2').openSegmentcorrectimport { openSegment } from 'aws-xray-sdk-koa2' - AWSXRay wrong
const AWSXRay = require('aws-xray-sdk-core')correctimport AWSXRay from 'aws-xray-sdk-core'
Quickstart
import Koa from 'koa';
import Router from '@koa/router';
import { openSegment } from 'aws-xray-sdk-koa2';
import AWSXRay from 'aws-xray-sdk-core';
const app = new Koa();
const router = new Router();
// Enable AWS X-Ray automatic mode
app.use(openSegment('defaultName'));
router.get('/', (ctx) => {
const segment = AWSXRay.getSegment();
segment?.addAnnotation('myAnnotation', 'value');
ctx.body = 'Hello, X-Ray!';
});
app.use(router.routes());
app.listen(3000);