X Enterprises
fastify-xlogger

extractContext(request)

Extract the canonical request context object from a Fastify request.

extractContext(request)

Extracts the canonical context fields from a Fastify request: requestId, route, method, and — when available — userId, orgId, traceId, and spanId. This is the same function used internally by request.contextLog and the onResponse hook.

Signature

fastify.xlogger.extractContext(
  request: FastifyRequest
): {
  requestId: string
  route: string
  method: string
  userId?: string
  orgId?: string
  traceId?: string
  spanId?: string
  [key: string]: unknown  // custom fields from contextExtractor
}

Params

NameTypeRequiredDescription
requestFastifyRequestYesThe Fastify request object

Returns

A plain object with context fields. Fields are only present when a value can be resolved.

Context resolution order

FieldResolution sources (first match wins)
userIdrequest.user.idrequest.user.userIdrequest.user.subx-user-id header
orgIdrequest.user.orgIdrequest.user.organizationIdrequest.user.tenantIdx-org-id header → x-tenant-id header
traceId / spanIdW3C traceparent header (version-traceId-spanId-flags)

Throws

Never throws.

Examples

Enrich a custom log entry

fastify.post("/webhooks/stripe", async (request) => {
  const context = fastify.xlogger.extractContext(request);

  fastify.log.info({
    ...context,
    event: "webhook.received",
    type: request.body.type,
  }, "Stripe webhook received");
});

Attach context to a queued message

fastify.post("/orders", async (request) => {
  const order = await createOrder(request.body);
  const context = fastify.xlogger.extractContext(request);

  await queue.publish("order.created", {
    orderId: order.id,
    _trace: context,  // carry context forward to async workers
  });

  return order;
});

See also

AI Context

package: "@xenterprises/fastify-xlogger"
method: fastify.xlogger.extractContext(request)
use-when: Manually extract requestId, route, method, userId, orgId, traceId, spanId from a request object — useful for enriching custom log entries or carrying context into queued messages
returns: plain context object (never throws)
Copyright © 2026