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

@dex-monit/observability-request-context

v1.0.2

Published

AsyncLocalStorage-based request context for Node.js applications

Readme

@dex-monit/observability-request-context

AsyncLocalStorage-based request context for Node.js applications. Provides request-scoped context without explicit parameter passing.

Installation

npm install @dex-monit/observability-request-context

Requirements

  • Node.js >= 16.0.0

Overview

This package provides a singleton RequestContextService that uses Node.js AsyncLocalStorage to maintain request-scoped data throughout the entire request lifecycle, including across async operations.

Features

  • ✅ Request-scoped context without manual parameter passing
  • ✅ Works across async/await and callbacks
  • ✅ Automatic propagation through the call stack
  • ✅ Type-safe with TypeScript
  • ✅ Zero dependencies (uses Node.js built-in async_hooks)

Usage

Basic Usage

import { RequestContextService } from '@dex-monit/observability-request-context';

// Start a context
RequestContextService.run(
  {
    requestId: 'req-123',
    transactionId: 'tx-456',
    startTime: Date.now(),
  },
  () => {
    // Access context anywhere in the call stack
    console.log(RequestContextService.getRequestId()); // 'req-123'
    
    // Call nested functions - context is available
    processRequest();
  }
);

function processRequest() {
  // Context is automatically available
  const ctx = RequestContextService.get();
  console.log(ctx?.requestId); // 'req-123'
}

With Express/NestJS

import { RequestContextService } from '@dex-monit/observability-request-context';
import { v4 as uuid } from 'uuid';

// Express middleware
app.use((req, res, next) => {
  RequestContextService.run(
    {
      requestId: req.headers['x-request-id'] || uuid(),
      transactionId: req.headers['x-transaction-id'],
      startTime: Date.now(),
    },
    () => next()
  );
});

Async Operations

import { RequestContextService } from '@dex-monit/observability-request-context';

RequestContextService.run(
  { requestId: 'req-123', startTime: Date.now() },
  async () => {
    // Context persists across async operations
    await someAsyncOperation();
    
    // Still available
    console.log(RequestContextService.getRequestId()); // 'req-123'
  }
);

API Reference

RequestContextData

interface RequestContextData {
  requestId: string;
  transactionId?: string;
  userId?: string;
  startTime: number;
  metadata?: Record<string, unknown>;
}

RequestContextService Methods

run<T>(context: RequestContextData, fn: () => T): T

Execute a function within a request context (synchronous).

const result = RequestContextService.run(
  { requestId: 'req-123', startTime: Date.now() },
  () => doSomething()
);

runAsync<T>(context: RequestContextData, fn: () => Promise<T>): Promise<T>

Execute an async function within a request context.

const result = await RequestContextService.runAsync(
  { requestId: 'req-123', startTime: Date.now() },
  async () => await doAsyncSomething()
);

get(): RequestContextData | undefined

Get the current context (returns undefined if not in a context).

const ctx = RequestContextService.get();
if (ctx) {
  console.log(ctx.requestId);
}

getOrThrow(): RequestContextData

Get the current context or throw if not available.

try {
  const ctx = RequestContextService.getOrThrow();
  console.log(ctx.requestId);
} catch (error) {
  console.error('Not in a request context');
}

getRequestId(): string | undefined

Shorthand to get the current request ID.

const requestId = RequestContextService.getRequestId();

getTransactionId(): string | undefined

Shorthand to get the current transaction ID.

const transactionId = RequestContextService.getTransactionId();

getUserId(): string | undefined

Shorthand to get the current user ID.

const userId = RequestContextService.getUserId();

update(updates: Partial<RequestContextData>): void

Update the current context with additional data.

RequestContextService.update({ userId: 'user-123' });

setMetadata(key: string, value: unknown): void

Set a metadata value on the current context.

RequestContextService.setMetadata('tenantId', 'tenant-456');

getMetadata<T>(key: string): T | undefined

Get a metadata value from the current context.

const tenantId = RequestContextService.getMetadata<string>('tenantId');

Integration with Logger

import { RequestContextService } from '@dex-monit/observability-request-context';
import pino from 'pino';

const logger = pino({
  mixin() {
    const ctx = RequestContextService.get();
    return ctx ? {
      requestId: ctx.requestId,
      transactionId: ctx.transactionId,
      userId: ctx.userId,
    } : {};
  },
});

// Logs automatically include request context
logger.info('Processing request'); 
// Output: {"requestId":"req-123","transactionId":"tx-456","msg":"Processing request"}

How It Works

This package uses Node.js AsyncLocalStorage from the async_hooks module. AsyncLocalStorage creates a storage that is available throughout the lifetime of an async operation, automatically propagating through:

  • Promise chains
  • async/await calls
  • setTimeout/setInterval callbacks
  • EventEmitter listeners
  • And more...

License

MIT