const fastify = require('fastify')();
fastify.addHook('preHandler', (request, reply, next) => {
let data = (function() {
// do something
return 'come from hook';
})();
request.ctx = data;
next();
});
fastify.get('/', function(request, reply) {
// decorate data
// do something
let responseData = 'decorate:' + request.ctx;
reply.send(responseData);
});
fastify.listen(3000, function(err) {
if (err) throw err;
console.log(`server listening on ${fastify.server.address().port}`);
});
I'm not sure if I'm doing the right way
Hi!
I'm not sure about what you need, but if you need to add some custom data to the request object inside the preHandler hook and then use it inside the handler, the most performant option is:
fastify.decorateRequest('ctx', '') // use the same type of the data you will add inside the preHandler hook
fastify.addHook('preHandler', (request, reply, next) => {
request.ctx = 'something'
next()
})
fastify.get('/', (request, reply) => {
reply.type('text/plain').send(request.ctx)// 'something'
})
By using the decorateRequest api, you will add that key to the request prototype instead of creating it every time at runtime (and altering the shape of the object), which is very performant.
I'm so sorry
this is the same issue #303
I mean that
OK, so you have already the answer :D
If you have more questions feel free to reopen! :)
Most helpful comment
Hi!
I'm not sure about what you need, but if you need to add some custom data to the request object inside the
preHandlerhook and then use it inside the handler, the most performant option is:By using the
decorateRequestapi, you will add that key to the request prototype instead of creating it every time at runtime (and altering the shape of the object), which is very performant.