aws / aws/aws-xray-sdk-node

need a hook or some other way to utilize the segment context elsewhere

Open
#489 2 comments 0 reactions 1 assignee Claimed by @srprash View on GitHub
Dominant language
JavaScript
Stars
280
Forks
157
PR merge metrics
No merged PRs in 30d

Description

Hi! I'm struggling to find a reasonable way to read and update the root Segment in an express app in automatic mode. This seems like a gap in functionality, apologies if I'm just missing something.

A few examples of things I'm trying to do:

* call `segment.setUser()` with the user from our auth middleware
* Log the `segment.trace_id` and/or add it to the response headers to make it easy to look up a trace for a specific request

I was hoping to just use an express middleware for this, something like:

```js
function addXRayContext(req, res, next) {
if (req.user)
AWSXRay.getSegment()?.setUser(req.user.id.toString())

const traceID = AWSXRay.getSegment()?.trace_id
if (traceID)
res.header('X-Amzn-Trace-Id', traceID)

next()
}
```

But if I inject that into my middleware stack I get the `cls-hooked` errors that the README warns about:

```js
app.use(AWSXRay.express.openSegment('solflow-api'))
app.use(addXRayContext) // doesn't work here
app.use(router)
app.use(AWSXRay.express.closeSegment())
```

I've dug through all the publicly exposed methods in the core and express packages and I haven't found anything that looks like it'll help me here -- the only option I can think of is to add a call to `addXRayContext` in every single route handler in our app, which of course would not be fun to maintain.

I think what I'm probably looking for is some way to hook into `traceRequestResponseCycle` after the root Segment is created. But maybe there's a better solution?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.