fastify / fastify/help

Decorators vs. fastify-request-context

Open
#759 3 comments 0 reactions 0 assignees View on GitHub
help wanted
Dominant language
No language data
Stars
68
Forks
8
Avg merge
11h 2m
Merged PRs (30d)
2

Description

## 💬 Question here

I have hard time understanding the difference between decorators that reset on every req vs. the fastify-request-context plugin.
If my handler looks like:
```
// Decorate request with a 'user' property
fastify.decorateRequest('user', null)

// Update our property
fastify.addHook('preHandler', (req, reply, done) => {
req.user = { id: 'system' }
done()
})

fastify.addHook('onRequest', (req, reply, done) => {
req.user.id = someCondition ? 'abc' : 'def'
done();
});

fastify.get('/', (req, reply) => {
reply.send(`Hello, ${req.user.a}!`) // expect 'abc' or 'def'
})
```

How would it happen that `req.user` gets overriden? Am I missing something? E.g. the code above should reflect the example in https://github.com/thorough-developer/fastify-http-context.
The readme in fastify-http-context and fastify-request-context mention that this prevents overriding things when multiple requests hit the same API endpoint - but is this correct? So if e.g. "/user/*" is waiting for the DB to load data for user X, and then some accesses user Y, it could happen that we get back "Hello, X" for the Y route?

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.