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
| Name | Type | Required | Description |
|---|---|---|---|
request | FastifyRequest | Yes | The Fastify request object |
Returns
A plain object with context fields. Fields are only present when a value can be resolved.
Context resolution order
| Field | Resolution sources (first match wins) |
|---|---|
userId | request.user.id → request.user.userId → request.user.sub → x-user-id header |
orgId | request.user.orgId → request.user.organizationId → request.user.tenantId → x-org-id header → x-tenant-id header |
traceId / spanId | W3C 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
- logEvent(params) — call
extractContextautomatically by passingrequest - createJobContext(params) — propagate context into background jobs
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)
