npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

aws-lambda-correlation-ids

v0.2.0

Published

Capture and pass correlation ids through event driven aws lambda invocations

Readme

aws-lambda-correlation-ids

This project is heavily inspired by https://github.com/getndazn/dazn-lambda-powertools and uses mostly the same concepts, the main divergences are:

  • It's BYOL (Bring Your Own Logger). Everyone has their favourite logger, and a specific logging integration doesn't add much benefit to this project - you can easily wrap your own logger to send the correlation ids (some loggers even have mixin methods which you can automatically inject the ids when the log methods run)
  • No middy dependency. Middy is not required for this lib, you simply use a wrap function to wrap your handler, alternatively if you are using middy then there is an optional captureCorrelationIds from the aws-lambda-correlation-ids/middleware subpath to join the middy chain directly. Either way your correlation ids will be available in any of your middlewares as well.
  • No SDK clients, dazn forced you to use their SDK clients but this locked you to a particular version dictated by the library. I could use peer dependencies but I liked the idea of zero dependencies overall and the client changes are small enough that we can simply intercept the relevent requests and inject the correlation ids as needed.

Automatically capture and propagate correlation ids through AWS Lambda invocations and the event sources that trigger them — API Gateway, SQS, SNS, EventBridge, Kinesis, Step Functions, and direct invokes — with no manual header/payload plumbing in your handler code.

  • Inbound: wrap() detects the event source and captures its correlation ids into an AsyncLocalStorage-backed scope before your handler runs.
  • Outbound: withCorrelationIds() wraps any AWS SDK v3 client so the ids you captured ride along automatically on the next SQS/SNS/Kinesis/EventBridge/Lambda/Step Functions call.
  • Anywhere in between: CorrelationIds.use() reads the active scope, for logging or for manually adding your own ids.
  • Zero dependencies: nothing in dependencies, peerDependencies, or otherwise — not even the AWS SDK. withCorrelationIds detects clients structurally at runtime instead of importing their types.

Install

npm install aws-lambda-correlation-ids

No AWS SDK packages are required as dependencies — withCorrelationIds works with any client shaped like { send(command) }, detected structurally at runtime.

Quick start

import { wrap, CorrelationIds } from "aws-lambda-correlation-ids";

export const handler = wrap(async (event, context) => {
  console.info({ msg: "handling request", ...CorrelationIds.use().get() });
  // ...
});
{
  msg: 'handling request',
  awsRequestId: '3b1f9e2a-req',
  'x-correlation-id': '3b1f9e2a-req',
  'call-chain-length': 1
}

wrap looks at the incoming event, figures out which service triggered the Lambda, and seeds the correlation-id scope accordingly (see Supported event sources). Everything your handler calls — synchronously or via await — can read that scope with CorrelationIds.use().

Core concepts

  • Correlation ids are a small bag of string key/value pairs, always including x-correlation-id and awsRequestId, plus a numeric call-chain-length that increments by one on every hop (Lambda invocation or fork()). You can add your own keys (see Injecting a custom id).
  • __context__: when this library needs to carry ids through a payload it doesn't otherwise control (an SQS message body, a Step Functions task's return value, a raw HTTP request you build yourself), it uses a __context__ key holding the correlation-id bag. wrap()'s event-source detection and withCorrelationIds()'s outbound decoration both read/write this same convention, so a payload produced by one composes with the other automatically.
  • Scope is per-invocation, powered by AsyncLocalStorage — no ids leak between concurrent invocations or between unrelated fork()ed units of work.

API

| Export | Signature | Purpose | | -------------------- | ----------------------------------------- | ----------------------------------------------------------------------- | | wrap | wrap(handler, options?) | Wrap a Lambda handler; captures inbound correlation ids before it runs. | | fork | fork(context, cb) | Run cb in a fresh child scope (e.g. one per SQS/Kinesis record). | | CorrelationIds | CorrelationIds.use() | Read the active scope: { get, set, clear, replace }. | | withCorrelationIds | withCorrelationIds(client) | Wrap an AWS SDK v3 client so outbound sends carry the active ids. | | constants | { X_CORRELATION_ID, CALL_CHAIN_LENGTH } | The literal header/key names, for manual propagation. |

Two subpath exports support per-record correlation ids in batched event sources:

| Export | Purpose | | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | aws-lambda-correlation-ids/event-sources/sqs | extractCorrelationIds(record) — read a single SQS record's inherited ids. | | aws-lambda-correlation-ids/event-sources/kinesis | extractCorrelationIds(record) — read a single Kinesis record's inherited ids. | | aws-lambda-correlation-ids/middleware | captureCorrelationIds(options?) — middy middleware alternative to wrap(), see Using Middy's own middleware interface. |

Examples

Logging with console

import { wrap, CorrelationIds } from "aws-lambda-correlation-ids";

const logger = {
  info: (msg: string) =>
    console.info({ msg, __context__: CorrelationIds.use().get() }),
  warn: (msg: string) =>
    console.warn({ msg, __context__: CorrelationIds.use().get() }),
  error: (msg: string) =>
    console.error({ msg, __context__: CorrelationIds.use().get() }),
};

export const handler = wrap(async (event, context) => {
  logger.info("handling request");
});
{
  msg: 'handling request',
  __context__: {
    awsRequestId: '3b1f9e2a-req',
    'x-correlation-id': '3b1f9e2a-req',
    'call-chain-length': 1
  }
}

Logging with AWS Lambda Powertools

Powertools' Logger.appendKeys() looks tempting here, but it snapshots whatever you pass it at the moment you call it. If you add a correlation id mid-handler (see Injecting a custom id), a key appended earlier won't pick up that change. Instead, wrap the logger so every call reads the current scope:

import { wrap, CorrelationIds } from "aws-lambda-correlation-ids";
import { Logger } from "@aws-lambda-powertools/logger";

const baseLogger = new Logger({ serviceName: "my-service" });

const LOG_METHODS = ["info", "warn", "error", "debug", "trace"] as const;
const logger = new Proxy(baseLogger, {
  get(target, prop, receiver) {
    const fn = Reflect.get(target, prop, receiver);
    if (
      typeof prop === "string" &&
      (LOG_METHODS as readonly string[]).includes(prop) &&
      typeof fn === "function"
    ) {
      return (message: string, ...rest: unknown[]) =>
        fn.call(
          target,
          message,
          { __context__: CorrelationIds.use().get() },
          ...rest,
        );
    }
    return fn;
  },
});

export const handler = wrap(async (event, context) => {
  logger.info("before set");
  CorrelationIds.use().set("userId", "user-42");
  logger.info("after set");
});
{
  "level": "INFO",
  "message": "before set",
  "timestamp": "2026-07-20T19:18:55.951Z",
  "service": "my-service",
  "sampling_rate": 0,
  "__context__": {
    "awsRequestId": "3b1f9e2a-req",
    "x-correlation-id": "3b1f9e2a-req",
    "call-chain-length": 1
  }
}
{
  "level": "INFO",
  "message": "after set",
  "timestamp": "2026-07-20T19:18:55.953Z",
  "service": "my-service",
  "sampling_rate": 0,
  "__context__": {
    "awsRequestId": "3b1f9e2a-req",
    "x-correlation-id": "3b1f9e2a-req",
    "call-chain-length": 1,
    "x-correlation-userId": "user-42"
  }
}

Logging with pino

pino's mixin option runs on every log call, so it's a good fit here too — return the active scope from it instead of wrapping each log method individually:

import { wrap, CorrelationIds } from "aws-lambda-correlation-ids";
import pino from "pino";

const logger = pino({
  mixin() {
    return { __context__: CorrelationIds.use().get() };
  },
});

export const handler = wrap(async (event, context) => {
  logger.info("handling request");
});
{
  "level": 30,
  "time": 1573664685466,
  "pid": 78742,
  "hostname": "x",
  "__context__": {
    "awsRequestId": "3b1f9e2a-req",
    "x-correlation-id": "3b1f9e2a-req",
    "call-chain-length": 1
  },
  "msg": "handling request"
}

Using with Middy

import middy from "@middy/core";
import jsonBodyParser from "@middy/http-json-body-parser";
import { captureCorrelationIds } from "aws-lambda-correlation-ids/middleware";

export const handler = middy(async (event, context) => {
  logger.info("something happened");
})
  .use(captureCorrelationIds())
  .use(jsonBodyParser());

Pass { propagateContext: true }, same as wrap()'s option, to merge the active ids into the resolved response under __context__ (see Step Functions):

.use(captureCorrelationIds({ propagateContext: true }))

Using without Middy

Just wrap() your handler directly — no other integration is required:

import { wrap } from "aws-lambda-correlation-ids";

export const handler = wrap(async (event, context) => {
  // ...
});

Injecting a custom id

Use CorrelationIds.use().set(key, value) anywhere inside a wrapped handler (or anything it calls). Keys that don't already start with x-correlation- are prefixed automatically, so they're picked up by every downstream hop the same way built-in ids are:

import { wrap, CorrelationIds } from "aws-lambda-correlation-ids";

export const handler = wrap(async (event, context) => {
  const userId = event.requestContext.authorizer?.userId;
  if (userId) {
    CorrelationIds.use().set("userId", userId); // stored as x-correlation-userId
  }
});
{
  awsRequestId: '3b1f9e2a-req',
  'x-correlation-id': '3b1f9e2a-req',
  'call-chain-length': 1,
  'x-correlation-userId': 'user-42'
}

Passing correlation ids to SQS processed records

An SQS batch can contain records from different upstream callers, so wrap() deliberately does not apply any one record's ids to the whole invocation. Use fork() with extractCorrelationIds() to give each record its own scope:

import { wrap, fork, CorrelationIds } from "aws-lambda-correlation-ids";
import { extractCorrelationIds } from "aws-lambda-correlation-ids/event-sources/sqs";
import type { SQSEvent } from "aws-lambda";

// wrap() is still required even though its batch-level capture is minimal:
// it opens the AsyncLocalStorage scope fork() forks from and seeds
// awsRequestId, which fork() reads onto every forked record.
export const handler = wrap(async (event: SQSEvent) => {
  for (const record of event.Records) {
    // Parse the correlation ids sent down in the SQS message record.
    await fork(extractCorrelationIds(record), async () => {
      // CorrelationIds.use() here resolves to this record's own ids
      console.info({ msg: "processing record", ...CorrelationIds.use().get() });
    });
  }
});
{
  msg: 'processing record',
  'x-correlation-id': 'upstream-abc',
  'call-chain-length': 3,
  awsRequestId: '3b1f9e2a-req'
}
{
  msg: 'processing record',
  'x-correlation-id': 'upstream-def',
  awsRequestId: '3b1f9e2a-req',
  'call-chain-length': 1
}

The same pattern applies to Kinesis via aws-lambda-correlation-ids/event-sources/kinesis.

fork()'s first argument isn't limited to extractCorrelationIds()'s return value — it also accepts a plain CorrelationIdsContext object or an existing CorrelationIdsInstance directly, for cases where you're building the ids yourself rather than parsing them off a record:

await fork({ "x-correlation-id": "manual-id" }, async () => {
  // CorrelationIds.use() resolves to a scope seeded from that object
});

Using a different client library (e.g. SST)

withCorrelationIds() only intercepts clients shaped like { send(command) }, matching known AWS SDK v3 command names. If something else is making the actual AWS call on your behalf — SST's event/bus client for EventBridge, or any other wrapper that doesn't expose the raw SDK command — withCorrelationIds never sees it, so attach __context__ to the payload yourself, the same way the library's own client wrappers do.

Since EventBridge is a supported inbound source, embedding __context__ in detail is enough — the receiving Lambda's wrap() picks it up automatically, no extra work on that end:

import { CorrelationIds } from "aws-lambda-correlation-ids";

// however your event client's publish function is shaped
await bus.publish("OrderCreated", {
  __context__: CorrelationIds.use().get(),
  orderId: "abc123",
});

Supported event sources

Detected automatically by wrap(), in this order:

| Source | Detection | Behavior | | ------------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------- | | API Gateway (REST v1 & HTTP v2) | httpMethod/requestContext shape | Reads x-correlation-* request headers; seeds apiRequestId. | | SQS | Records[0].eventSource === "aws:sqs" | Fresh scope at the batch level (see per-record forking). | | SNS | Records[0].EventSource === "aws:sns" | Reads __context__ from the first record's message. | | EventBridge | has detail/detail-type/source | Reads __context__ from event.detail. | | Kinesis | Records[0].eventSource === "aws:kinesis" | Fresh scope at the batch level (see per-record forking). | | Direct invoke / Step Functions | event carries a top-level __context__ | Covers both a direct Lambda-to-Lambda invoke and a Step Functions task receiving the previous state's output. | | DynamoDB Streams | — | Coming soon. | | (fallback) | anything else (ALB, S3, custom triggers) | Starts a fresh chain from awsRequestId; no upstream ids to inherit. |

Supported outbound clients

withCorrelationIds(client) decorates these commands, injecting __context__ into their JSON payload:

| Service | Commands | | -------------- | ----------------------------------------------- | | SQS | SendMessageCommand, SendMessageBatchCommand | | SNS | PublishCommand, PublishBatchCommand | | Lambda | InvokeCommand | | Step Functions | StartExecutionCommand | | Kinesis | PutRecordCommand, PutRecordsCommand | | EventBridge | PutEventsCommand | | DynamoDB | Coming soon. |

Any other command passes through untouched.

Step Functions

Opt a task handler in with { propagateContext: true } to merge the active ids into its resolved return value under __context__. Auto-detection on the next task only works if __context__ stays at the top level of its input, which holds with the default ResultPath (the task's raw output becomes the next state's input untouched) — but a ResultPath that nests the result (e.g. "ResultPath": "$.taskResult") or a Parameters/InputPath on the next state that reshapes the payload will move or drop __context__, silently breaking propagation. Keep the default ResultPath, or explicitly carry $.__context__ through if you're customizing it.

export const handler = wrap(
  async (event) => {
    return { orderId: "abc123" }; // becomes { __context__: {...}, orderId: "abc123" }
  },
  { propagateContext: true },
);
{
  __context__: {
    awsRequestId: '3b1f9e2a-req',
    'x-correlation-id': '3b1f9e2a-req',
    'call-chain-length': 1
  },
  orderId: 'abc123'
}