Skip to content

Context ​

Introduction ​

Some information belongs to a whole unit of work rather than to any one function: the id of the current request, the signed-in user, a trace id, the tenant. Passing it as an argument through every layer is tedious, and storing it in a module-level variable is wrong, because many requests are in flight at the same time.

Context solves this. It is a small store of key and value pairs that follows the asynchronous flow of your code. Anything you put in it while handling a request can be read from any function that request calls, however deep and however many awaits away, and it is invisible to every other request running at the same moment. It is built on Node's AsyncLocalStorage and lives in @plinthjs/core.

ts
import { Context } from '@plinthjs/core'

await Context.run({ requestId: 'abc-123' }, async () => {
  await handle()
})

async function handle() {
  await somethingAsync()
  Context.get('requestId') // => 'abc-123'
}

Opening a Scope ​

Values only exist inside a scope. Context.run(initial, callback) creates a fresh store seeded with the values in initial, runs the callback inside it, and returns whatever the callback returns (the promise itself, if the callback is async).

ts
const result = await Context.run({ requestId: 'abc' }, async () => {
  await new Promise((resolve) => setTimeout(resolve, 5))
  Context.set('userId', 7)
  return Context.all()
})
// => { requestId: 'abc', userId: 7 }

Everything started inside the callback shares the scope: awaited calls, promise chains, timers and event callbacks created within it all see the same store. Two scopes that run at the same time are completely separate.

ts
await Promise.all([
  Context.run({ name: 'one' }, async () => {
    await delay(5)
    return Context.get('name')
  }), // => 'one'
  Context.run({ name: 'two' }, async () => {
    await delay(5)
    return Context.get('name')
  }), // => 'two'
])

WARNING

Nothing in the framework opens a scope for you. The HTTP kernel, queue workers and console commands do not call Context.run, so you must do it yourself, typically in a global middleware (see Opening a Scope Per Request). Outside any scope, reads return nothing and writes are silently dropped.

Reading and Writing Values ​

Inside a scope, these functions read and change the store:

ts
Context.run({ requestId: 'abc' }, () => {
  Context.get<string>('requestId') // => 'abc'
  Context.get('missing') // => undefined

  Context.set('user', { id: 7 })
  Context.has('user') // => true

  Context.all() // => { requestId: 'abc', user: { id: 7 } }

  Context.forget('user')
  Context.has('user') // => false
})

get takes an optional type argument for the value you expect, which is a cast and not a check. all() returns a plain-object copy, so changing the returned object does not change the store. Values you set deep inside the call chain are visible to the code that started it, because they share one store.

Outside a Scope ​

When no scope is active, the store simply is not there. get returns undefined, has returns false, all returns an empty object, and set and forget do nothing and do not throw.

ts
Context.set('x', 1) // silently ignored
Context.get('x') // => undefined

This makes code that reads context safe to run in a unit test or a script without any setup. It also means a value you set before opening a scope is lost, so always open the scope first.

Nested Scopes ​

A nested Context.run starts a new, empty store seeded only with its own initial values. It does not inherit from the scope around it, and when it finishes the outer scope is unchanged.

ts
Context.run({ a: 1 }, () => {
  Context.run({ b: 2 }, () => {
    Context.all() // => { b: 2 }
  })
  Context.all() // => { a: 1 }
})

If you want the inner scope to keep the outer values, pass them in: Context.run({ ...Context.all(), b: 2 }, callback).

Opening a Scope Per Request ​

The natural place to open a scope is a global middleware, so that everything a request touches shares it.

ts
import { Context } from '@plinthjs/core'

import type { Middleware } from '@plinthjs/http'

export function requestContext(): Middleware {
  return (request, next) =>
    Context.run({ requestId: crypto.randomUUID(), path: request.path() }, () => next(request))
}

Any controller, service or model called while the request is handled can now read Context.get('requestId'). The same approach works for a queue job or a scheduled task: wrap the unit of work in Context.run.

Context in Log Lines ​

A log line is much more useful when it says which request produced it. A logger can attach a Context repository from @plinthjs/logging (a different class, covered below) so its values ride on every record. To use the request-scoped store from this page instead, wrap a handler so each record is enriched when it is written:

ts
import { Context } from '@plinthjs/core'
import { ArrayHandler, Logger } from '@plinthjs/logging'

import type { Handler, LogRecord } from '@plinthjs/logging'

const inner = new ArrayHandler()

const scoped: Handler = {
  level: 'debug',
  isHandling: (level) => inner.isHandling(level),
  handle: (record: LogRecord) =>
    inner.handle({ ...record, context: { ...Context.all(), ...record.context } }),
}

const log = new Logger('app', [scoped])

Context.run({ requestId: 'rq-9' }, () => log.info('inside', { a: 1 }))
log.info('outside')

inner.records.map((r) => r.context)
// => [{ requestId: 'rq-9', a: 1 }, {}]

Replace ArrayHandler with a file or console handler in a real application. See Logging.

The Logging Context Repository ​

@plinthjs/logging exports its own class, also named Context, which is a different tool. It is an ordinary object you create and pass around (not tied to the async flow). It keeps two compartments of data: visible data, which is merged into every log record when the repository is attached to a logger, and hidden data, which is carried along but never written to a log line. It also offers stacks for building up a trail of breadcrumbs, and a way to package its content up and restore it elsewhere, for example when a job is queued.

ts
import { Context as LogContext } from '@plinthjs/logging'

const context = new LogContext()
context.add('request_id', 'r-1') // visible, appears in log lines
context.addHidden('token', 'secret') // never appears in log lines
context.push('crumbs', 'a', 'b') // append to a visible array

Import it under another name if you also use the core Context in the same file.

Visible Data ​

ts
context.add('plan', 'pro') // one value
context.add({ locale: 'en', region: 'eu' }) // several at once; later keys win

context.has('plan') // => true
context.missing('nope') // => true
context.get('plan') // => 'pro'
context.all() // => { request_id: 'r-1', crumbs: [...], plan: 'pro', ... } (a copy)
context.only(['plan', 'locale']) // => just those keys; absent keys are omitted
context.forget('plan') // one key
context.forget(['locale', 'region']) // or several

push(key, ...values) appends to an array, creating it if needed, and throws Unable to push value onto context stack for key [key]. when the key already holds something that is not an array.

Hidden Data ​

Hidden data has its own methods: addHidden, hasHidden, getHidden, allHidden, onlyHidden, forgetHidden and pushHidden. It never reaches a log record, which makes it the place for tokens, user payloads or anything sensitive that must travel with the request.

ts
context.addHidden('token', 'secret')
context.getHidden('token') // => 'secret'
context.get('token') // => undefined (visible and hidden are separate)

Conditional and Housekeeping Helpers ​

when(condition, callback, otherwise?) runs a callback against the repository when a condition holds, isEmpty() is true when both compartments are empty, and flush() clears everything.

ts
context.when(user !== null, (c) => c.add('user_id', user.id))

Attaching It to a Logger ​

Pass the repository to a logger, or to a LogManager to apply it to every channel. Its visible data is added to every record, with the lowest precedence: shared and per-call context win when a key collides. The repository stays live, so values added later appear in later records.

ts
import { ConsoleHandler, JsonFormatter, Logger } from '@plinthjs/logging'

const log = new Logger('c', [new ConsoleHandler('debug', { formatter: new JsonFormatter() })], {
  contextRepository: context,
})

log.info('hi', { extra: 1 })
// {"level":"info","message":"hi","context":{"request_id":"r-1","crumbs":["a","b"],"extra":1}, ...}

You can also attach one later with logger.attachContext(context).

Dehydrating and Hydrating ​

dehydrate() returns a plain, deep-copied snapshot of both compartments (or null when the repository is empty). hydrate(snapshot) replaces a repository's whole state from a snapshot. Together they let context cross a boundary such as a queue: take the snapshot when you dispatch work, store it with the job payload, and hydrate a fresh repository in the worker.

ts
const snapshot = context.dehydrate()
// => { data: { request_id: 'r-1', crumbs: ['a', 'b'] }, hidden: { token: 'secret' } }

// later, in the worker
const restored = new LogContext().hydrate(snapshot)
restored.all() // => { request_id: 'r-1', crumbs: ['a', 'b'] }
restored.allHidden() // => { token: 'secret' }

new LogContext().dehydrate() // => null

Hydrating with null or undefined just empties the repository. Because the snapshot is a deep copy, later changes to the original do not leak into it.

Testing ​

Context is easy to test because outside a scope it does nothing. Wrap the code under test in Context.run with the values you want it to see, and assert on what it returns or logs.

ts
const id = Context.run({ requestId: 'test-1' }, () => currentRequestId())
// => 'test-1'

Released under the MIT License.