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

express-typed-context

v1.0.0

Published

TypeScript-first AsyncLocalStorage wrapper for Express. Propagate per-request context (requestId, userId, traceId) through your entire async call chain — no req threading required.

Readme

express-typed-context

npm version License: MIT Node.js TypeScript

TypeScript-first AsyncLocalStorage wrapper for Express.

Propagate per-request context (request ID, user ID, trace ID) through your entire async call chain — without threading req through every function.


The Problem

// ❌ Without this library — req threads through everything
async function getUser(req: Request) {
  const user = await db.findById(req.user.id);
  await logger.info(req.requestId, "User fetched");     // req needed everywhere
  await audit.log(req.requestId, req.user.id, "read");  // and everywhere
  return user;
}
// ✅ With this library — ctx is available anywhere, no req passing needed
async function getUser() {
  const { requestId, userId } = ctx.getOrThrow(); // just works, no req
  const user = await db.findById(userId);
  await logger.info("User fetched");   // requestId auto-injected by createContextLogger
  await audit.log("read");             // same here
  return user;
}

How It Works

Node.js AsyncLocalStorage (stable since v16.4) creates a "store" that automatically travels through await, .then(), setTimeout, callbacks — anything that originated in the same async chain. This library wraps that in a typed, Express-friendly API.


Installation

npm install express-typed-context

Requirements: Node.js ≥ 16.4.0, Express ≥ 4.0.0


Quick Start

import express from "express";
import { createRequestContext, requestIdInitializer } from "express-typed-context";

// 1. Define your context shape
interface AppContext {
  requestId: string;
  userId?: string;
}

// 2. Create typed context utilities (one instance per app)
export const ctx = createRequestContext<AppContext>({ name: "app" });

const app = express();

// 3. Mount middleware — seeds context at the start of every request
app.use(ctx.middleware(requestIdInitializer()));

// 4. Enrich context later (e.g. after auth)
app.use(authMiddleware);
app.use((req, res, next) => {
  ctx.set({ userId: req.user?.id }); // merges — doesn't replace requestId
  next();
});

// 5. Read anywhere — no req needed
app.get("/profile", async (req, res) => {
  const profile = await getUserProfile(); // this function calls ctx internally
  res.json(profile);
});

async function getUserProfile() {
  const { requestId, userId } = ctx.getOrThrow(); // fully typed
  return db.users.findById(userId);
}

API Reference

createRequestContext<T>(options?)

The main factory. Creates a fully-typed context backed by its own AsyncLocalStorage instance.

const ctx = createRequestContext<{ requestId: string; userId?: string }>({
  name: "app",   // used in error messages; optional, default: "default"
  strict: false, // if true, get() also throws outside context; default: false
});

Returns a RequestContextAPI<T> object:

| Method | Signature | Description | |--------|-----------|-------------| | middleware | (initializer: (req) => T) => ExpressMiddleware | Mount this with app.use(). Seeds the context from the request. | | get | () => T \| undefined | Returns current store, or undefined outside a request. | | getOrThrow | () => T | Returns current store, or throws ContextNotFoundError with a helpful message. | | set | (patch: Partial<T>) => void | Merges a partial update into the current store. Does NOT replace. | | run | (initialValue: T, callback: () => R) => R | Run a callback inside a manually-provided context (for background jobs / tests). | | fork | (extra?: Partial<T>) => ChildContext | Creates a child context inheriting the parent's fields + extra fields. |


requestIdInitializer(options?)

A ready-made initializer that reads x-request-id from incoming headers (for distributed tracing) and falls back to a UUID.

app.use(ctx.middleware(requestIdInitializer({
  headerName: "x-request-id", // default
  generator: () => crypto.randomUUID(), // default
})));

| Option | Type | Default | Description | |--------|------|---------|-------------| | headerName | string | "x-request-id" | Header to read the request ID from. | | generator | () => string | crypto.randomUUID() | Called when the header is absent. |


createContextLogger(context, baseLogger)

Wraps any logger to automatically prepend request context to every log call. Works with pino, winston, or console — no hard dependency.

import pino from "pino";
import { ctx } from "./context";
import { createContextLogger } from "express-typed-context";

const logger = createContextLogger(ctx, pino());

// In any service — requestId injected automatically:
logger.info("User logged in");
// → {"requestId":"abc-123","level":30,"msg":"User logged in"}

Background Jobs: ctx.run() and ctx.fork()

For work that escapes the request's async chain:

// Inherit request context into a background job
app.post("/send-email", async (req, res) => {
  res.json({ ok: true }); // respond immediately

  // Fork the context so the background job carries requestId for tracing
  const child = ctx.fork({ jobId: crypto.randomUUID() });
  setImmediate(() => {
    child.run(child.get()!, () => sendWelcomeEmail(req.body.userId));
  });
});

// Completely manual context (e.g., cron jobs, queue consumers)
async function processQueueJob(jobId: string) {
  await ctx.run({ requestId: `job-${jobId}` }, async () => {
    await doWork(); // getOrThrow() works inside here
  });
}

Testing Utilities

Import from express-typed-context/testing:

import { withMockContext } from "express-typed-context/testing";
import { ctx } from "../src/context";

test("getUser reads userId from context", async () => {
  await withMockContext(ctx, { requestId: "test-123", userId: "user-456" }, async () => {
    const user = await getUser(); // calls ctx.getOrThrow() internally
    expect(user.id).toBe("user-456");
  });
});

Error Handling

getOrThrow() and set() throw ContextNotFoundError with clear, actionable messages:

[express-typed-context:app] Cannot call "getOrThrow()": no active request context found.

Possible causes:
  1. You forgot to mount the context middleware:
       app.use(ctx.middleware(req => ({ ... })))
  2. You called getOrThrow() in a background job that escaped the request's async chain.
     Use ctx.run(initialValue, callback) to wrap background jobs explicitly.
  3. You called getOrThrow() at module load time, before any request was made.

In development (NODE_ENV !== "production"), get() also emits a warning with a stack trace when called outside context.


Why Not...?

| Package | Problem | |---------|---------| | cls-hooked | Deprecated, uses old async_hooks monkey-patching, memory leaks, no TypeScript generics | | express-http-context | Stale, get('key') returns any — no typed store shape | | @fastify/request-context | Great, but Fastify-only | | nestjs-cls | Great, but NestJS DI system-only |

This package: actively maintained, TypeScript generics via createRequestContext<T>(), proper dual CJS+ESM build, zero runtime dependencies.


License

MIT