Fastify: How can I transfer data to routing in hook?

Created on 16 Nov 2017  路  3Comments  路  Source: fastify/fastify

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

question

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 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.

All 3 comments

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! :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

PacoDu picture PacoDu  路  3Comments

valentinvichnal picture valentinvichnal  路  3Comments

mcollina picture mcollina  路  3Comments

lfurzewaddock picture lfurzewaddock  路  3Comments

rabbitooops picture rabbitooops  路  3Comments