Runtime

Request Context

Read the request ID, user and tenant anywhere in a Node.js call stack with requestContext(), getContext() and runWithContext() from @axiljs/runtime.

5 min readUpdated DocumentationEdit this page
On this page8

requestContext() opens one AsyncLocalStorage store per HTTP request. Everything that runs downstream, including middleware, the handler, services, repositories and interceptors, can read it with getContext(), without threading req through every function.

TypeScript
TS
1import { Application } from '@axiljs/core'
2import { requestContext, getContext } from '@axiljs/runtime'
3
4const app = new Application()
5app.use(requestContext())   // register early, before auth
6
7app.get('/orders', async (_req, res) => {
8  res.success(await orders.list())
9})
10
11// orders.ts, no req parameter needed
12export const orders = {
13  async list() {
14    const ctx = getContext()
15    console.log(`[${ctx?.requestId}] listing orders for tenant ${ctx?.tenantId}`)
16    return []
17  }
18}

requestContext(options?)

Returns a middleware that opens the context and calls next() inside it. The rest of the pipeline runs from inside that next() call, so the store follows every downstream middleware and the handler, across awaits.

OptionTypeDefaultDescription
headerstring'x-request-id'Request header to read an incoming request ID from, and the response header to echo it in
echoHeaderbooleantrueSet the request ID on the response header
generateId() => stringcrypto.randomUUIDGenerator used when no usable ID is supplied
TypeScript
TS
1app.use(requestContext({
2  header: 'x-correlation-id',
3  generateId: () => `req_${Date.now().toString(36)}`
4}))

Note

Node.js lower-cases incoming header names, so pass header in lower case.

Tip

Register requestContext() as global middleware, before authentication and tenancy middleware. Code that runs before it, or outside the request pipeline, sees getContext() return undefined.

How the request ID is chosen

The middleware picks the first of:

  1. req.locals.requestId, when an earlier middleware already set a non-empty string.
  2. The incoming header (x-request-id by default), only if it is valid: 1 to 128 characters from letters, digits, _, ., : and -. When the header is repeated, the first value is used.
  3. generateId(), which defaults to crypto.randomUUID().

The chosen ID is written back to req.locals.requestId and, unless echoHeader: false, set on the response header.

Anything that fails validation, such as a value containing spaces, CR/LF or more than 128 characters, is ignored and a fresh ID is generated. A client cannot inject headers or log lines through the request ID.

Terminal
❯curl -i -H "x-request-id: trace-me-1" http://localhost:3000/orders
# x-request-id: trace-me-1
❯curl -i -H "x-request-id: bad id" http://localhost:3000/orders
# x-request-id: 3b0c8f5e-... (fresh UUID)

Because the ID is also on req.locals.requestId, error handlers can include it in error bodies:

TypeScript
TS
1app.use((err, req, res, _next) => {
2  res.status(500).json({
3    error: { code: 'INTERNAL_ERROR', message: err.message, requestId: req.locals.requestId }
4  })
5})

getContext()

Returns the current RequestContext, or undefined outside requestContext() and runWithContext().

FieldTypeDescription
requestIdstringCorrelation ID for this request, job or task
startedAtnumberDate.now() when the context was opened
reqaxilRequest | undefinedThe request this context belongs to. Absent for jobs and tasks
userobject | undefinedreq.locals.user, as set by @axiljs/auth. Shape: { id, type?, tenantId?, ... }
tenantIdstring | undefinedreq.locals.tenant.id (set by @axiljs/cloud multi-tenancy), else user.tenantId
bagMap<string, unknown>Free-form per-request storage

All fields are read-only.

user and tenantId are lazy

user and tenantId are getters that read req.locals each time you access them, not when the context is created. That is why requestContext() can run before your auth middleware: once authentication sets req.locals.user, every later getContext()?.user sees it.

TypeScript
TS
1app.use(requestContext())
2app.use(authenticate(jwt))            // sets req.locals.user later in the chain
3
4app.get('/me', (_req, res) => {
5  res.success({ userId: getContext()?.user?.id })   // populated
6})

The tenantId lookup order is: an explicit tenantId (from runWithContext()), then req.locals.tenant.id, then user.tenantId.

The bag

bag is a plain Map scoped to one request. Use it for values that are computed once per request and needed deep in the stack, such as a feature-flag snapshot or a per-request cache.

TypeScript
TS
1import { getContext } from '@axiljs/runtime'
2
3export async function currentPlan(): Promise<string> {
4  const bag = getContext()?.bag
5  const cached = bag?.get('plan') as string | undefined
6  if (cached) return cached
7
8  const plan = await loadPlanFromDb()
9  bag?.set('plan', plan)
10  return plan
11}

The bag is discarded with the context when the request ends.

runWithContext(init, fn)

Runs fn inside a fresh context. Use it where there is no HTTP request: queue jobs, cron tasks, CLI scripts and tests. It returns whatever fn returns (including a Promise).

init fieldTypeDefault
requestIdstringcrypto.randomUUID()
user{ id, type?, tenantId?, ... }undefined
tenantIdstringuser.tenantId
TypeScript
TS
1import { runWithContext } from '@axiljs/runtime'
2
3async function nightlyInvoices() {
4  await runWithContext(
5    { requestId: `cron-invoices-${Date.now()}`, user: { id: 'billing-bot', type: 'service' } },
6    () => invoices.generateAll()      // wired methods inside audit as billing-bot
7  )
8}

Carry the ID of the request that enqueued a job, so logs and audit events of both share one correlation ID:

TypeScript
TS
1// in the request: put the ID on the job payload (enqueue = your queue's API)
2await enqueue('send-receipt', { orderId, requestId: getContext()?.requestId })
3
4// in the worker
5async function handle(job: { orderId: string; requestId?: string }) {
6  return runWithContext({ requestId: job.requestId }, () => receipts.send(job.orderId))
7}

Outside any context, tAudit records the actor as { id: 'system', type: 'system' }. Wrapping jobs in runWithContext() with a user gives them a meaningful actor instead.

Testing

runWithContext() is also the simplest way to test code that calls getContext():

TypeScript
TS
1import { describe, it, expect } from '@axiljs/testing'
2import { runWithContext } from '@axiljs/runtime'
3
4describe('orders', () => {
5  it('scopes to the tenant in context', async () => {
6    const result = await runWithContext({ tenantId: 'acme' }, () => orders.list())
7    expect(result).toEqual([])
8  })
9})

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY