# Configure elastic-apm-node

**URL:** https://discuss.elastic.co/t/configure-elastic-apm-node/337272
**Category:** APM
**Tags:** nodejs
**Created:** [June 30, 2023, 6:35am UTC](https://discuss.elastic.co/t/configure-elastic-apm-node/337272 "2023-06-30T06:35:25Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![Supun\_Madushanka](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/supun_madushanka/32/79828_2.png) [@Supun\_Madushanka](https://discuss.elastic.co/u/Supun_Madushanka)
#### Post date: [June 30, 2023, 6:35am UTC](https://discuss.elastic.co/t/configure-elastic-apm-node/337272/1 "2023-06-30T06:35:25Z")

</div>

elastic cloud latest version

```auto
const config = require('./config');
const apm = require('elastic-apm-node').start({
    serviceName: config.ELASTIC_APM_SERVICE_NAME,
    secretToken: config.ELASTIC_APM_SERVICE_SECRET,
    serverUrl: config.ELASTIC_APM_SERVER_URL,
    environment: config.ELASTIC_APM_ENV,
  })
function globalUser (payload) {
  if (payload.context &&
      payload.context.request &&
      payload.context.request.headers &&
      payload.context.request.headers['x-user-id']) {
    // redact sensitive data
    const xUserId = payload.context.request.headers["x-user-id"]
    console.log(xUserId)
    apm.setUserContext({id: xUserId})
  }
  
  return payload // remember to return the modified payload
}
apm.addFilter(globalUser)
module.exports = apm;

```

this is not updated user.id

---

<div class="post-metadata">

### Author: ![trentm](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/trentm/32/77647_2.png) [@trentm](https://discuss.elastic.co/u/trentm)
#### Post date: [June 30, 2023, 3:25pm UTC](https://discuss.elastic.co/t/configure-elastic-apm-node/337272/2 "2023-06-30T15:25:31Z")

</div>

Hi @Supun_Madushanka.

Functions added via `apm.addFilter` are invoked **just before** tracing data is sent to the APM server. At this point the span or transaction has already ended, which means that `apm.setUserContext(...)` -- which is an API to change the **active** transaction -- will not operate on the `payload` data in that function.

You said (in your Slack post) that this was an Express app. What will probably work better would be to create a small Express middleware function that does a similar thing. Something like this:

```js
app.use(function (req, res, next) {
  const userId = req.headers['x-user-id']
  if (userId) {
    apm.setUserContext({id: userId})
  }
  next()
})

```

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)
#### Post date: [July 28, 2023, 3:26pm UTC](https://discuss.elastic.co/t/configure-elastic-apm-node/337272/3 "2023-07-28T15:26:24Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
