Class: AsyncContextId

AsyncContextId(optionsopt) → {AsyncContextId}

A singleton class that tracks correlation IDs across asynchronous operations in Node.js. Uses async_hooks to automatically propagate correlation context across async boundaries.

Constructor

new AsyncContextId(optionsopt) → {AsyncContextId}

This class provides context propagation across async operations in Node.js applications. It maintains correlation IDs and metadata throughout the async execution chain.
Parameters:
Name Type Attributes Default Description
options Object <optional>
{} Configuration options
Properties
Name Type Attributes Default Description
store Map <optional>
new Map() Optional Map instance for context storage, this package includes both a LRU ( Least Recently Used ) Map and a Timed Map.
correlationIdFn fn <optional>
Optional function to override default UUID generation. Should return a string
Properties:
Name Type Description
contextStore Map Storage for async context data
hook AsyncHook The async_hooks instance for tracking async operations
cleanUpFn function Cleanup function registered for process exit
Source:
Tutorials:
Returns:
The singleton instance
Type
AsyncContextId
Examples
// Using default Map and UUID generation
const tracker = new AsyncContextId();
// Using custom LRU Map and correlation ID generator
const tracker = new AsyncContextId({
  store: new LruMap(1000),
  correlationIdFn: () => `custom-${Date.now()}`
});

Methods

cleanUpFn()

remove the listener of itself to prevent memory leaks
Source:

clear()

Removes the correlation context for the current async operation.
Source:
Throws:
If async hooks are not enabled
Type
Error
Example
try {
  await processRequest(data);
} finally {
  tracker.clear();
}

getContext() → {Object|string|number|Object}

Retrieves the complete context object for the current async operation. Creates a new context if none exists.
Source:
Throws:
If async hooks are not enabled
Type
Error
Returns:
  • The correlation context
    Type
    Object
  • context.correlationId - The correlation ID
    Type
    string
  • context.startTime - Unix timestamp of context creation
    Type
    number
  • context.metadata - Custom metadata object
    Type
    Object
Example
const context = tracker.getContext();
console.log({
  correlationId: context.correlationId,
  duration: Date.now() - context.startTime,
  metadata: context.metadata
});

getCorrelationId() → {string}

Retrieves the correlation ID for the current async context. Creates a new context with generated ID if none exists.
Source:
Throws:
If async hooks are not enabled
Type
Error
Returns:
The current correlation ID
Type
string
Example
const correlationId = tracker.getCorrelationId();
res.setHeader('x-correlation-id', correlationId);

setContext(contextopt)

Updates the context for the current async operation. Creates a new context if none exists. Preserves existing correlationId and startTime unless explicitly overridden.
Parameters:
Name Type Attributes Default Description
context Object <optional>
{} The context object to merge
Properties
Name Type Attributes Description
correlationId string <optional>
Optional correlation ID override
metadata Object <optional>
Optional metadata to merge
Source:
Throws:
  • If async hooks are not enabled
    Type
    Error
  • If context is not an object
    Type
    Error
Example
// Add request context
tracker.setContext({
  metadata: {
    operation: 'processData',
    requestId: req.id,
    userId: req.user.id
  }
});

setCorrelationId(correlationId)

Sets the correlation ID for the current async context. Creates a new context if none exists.
Parameters:
Name Type Description
correlationId string The correlation ID to set
Source:
Throws:
  • If the correlationId is not a string
    Type
    Error
  • If async hooks are not enabled
    Type
    Error
Example
const upstreamId = req.headers['x-correlation-id'];
if (upstreamId) {
  tracker.setCorrelationId(upstreamId);
}