Minimal, type-safe execution context utilities for Node.js based on AsyncLocalStorage
npm install @pfeiferio/ctxMinimal utilities for execution-scoped context in Node.js using AsyncLocalStorage.
@pfeiferio/ctx lets you safely create, access and bind logic to an asynchronous execution context — without passing state through every function.
---
* Execution-scoped context via AsyncLocalStorage
* Fully type-safe & generic
* Context guards (bindToCurrentContext)
* Works with sync and async code
* No dependencies
---
``bash`
npm install @pfeiferio/ctx
---
A context is data that is bound to the current asynchronous execution flow.
Typical use cases:
* request / job scoped state
* authentication or tenant data
* correlation IDs
* logging & tracing
---
`ts`
type RequestContext = {
requestId: string
userId?: string
}
---
`ts
import { runWithContext } from '@pfeiferio/ctx'
await runWithContext
{
requestId: 'req-123',
userId: 'u-42',
},
async () => {
// all code here shares the same context
}
)
`
---
`ts
import { getContext } from '@pfeiferio/ctx'
const ctx = getContext
if (ctx) {
console.log(ctx.requestId)
}
`
getContext returns undefined when called outside a context.
---
bindToCurrentContext ensures a function can only execute
inside the context it was created in.
`ts
import { bindToCurrentContext } from '@pfeiferio/ctx'
const sendResponse = bindToCurrentContext<
RequestContext,
[string],
void
>((message) => {
console.log('response:', message)
})
`
Later:
`ts`
sendResponse('ok') // executed (same context)
sendResponse('invalid') // no-op if context changed
---
`ts
type LogContext = {
requestId: string
}
const log = (msg: string) => {
const ctx = getContext
console.log([${ctx?.requestId ?? 'global'}], msg)
}
await runWithContext
{ requestId: 'req-99' },
async () => {
log('start')
await doSomethingAsync()
log('done')
}
)
`
---
`ts
const guardedFn = bindToCurrentContext<
unknown,
[],
void
>(() => {
console.log('safe execution')
})
// calling outside the context → no-op
guardedFn()
`
---
Runs fn inside a new execution context.
---
Returns the current context or undefined`.
---
Binds a function to the current execution context.
---
* explicit over implicit
* runtime safety over magic
* no global mutable state exposure
* minimal surface area
---
* framework integration
* request lifecycle management
* cross-process context propagation
---
MIT