6

I need to access the fastify instance from a handler file. I don't remember at all how I should be doing that.

index:

fastify.register(require('./routes/auth'), {
  prefix: '/auth'
})

routes/auth:

module.exports = function(fastify, opts, next) {
  const authHandler = require('../handlers/auth')
  fastify.get('/', authHandler.getRoot)
  next()
}

handler/auth:

module.exports = {
  getRoot: (request, reply) {
    // ACCESS FASTIFY NAMESPACE HERE
    reply.code(204).send({
      type: 'warning',
      message: 'No content'
    })
  }
}

Thanks!

4 Answers 4

6

fastify.decorateRequest('fastify', fastify); Will now return a warning message:

FastifyDeprecation: You are decorating Request/Reply with a reference type. This reference is shared amongst all requests. Use onRequest hook instead. Property: fastify

Here is the updated usage for the OnRequest hook for requests:

fastify.decorateRequest('fastify', null)    
fastify.addHook("onRequest", async (req) => {
        req.fastify = fastify;
}); 

Replace "onRequest" with "onReply" if needed for replies. See Fastify docs on it here.

4

Update:
you can use this keyword for accessing fastify instance in your controllers that are defined with function keyword. Arrow function controllers won't work.

You can also decorate fastify instance on request or reply object:

index:

fastify.decorateRequest('fastify', fastify);
// or
fastify.decorateReply('fastify', fastify);

fastify.register(require('./routes/auth'), {
  prefix: '/auth'
});

Then in your handler/auth:

module.exports = {
  getRoot: (request, reply) {
    // ACCESS FASTIFY NAMESPACE HERE
    request.fastify
    // or
    reply.fastify

    reply.code(204).send({
      type: 'warning',
      message: 'No content'
    });
  }
};
2

routes/auth:

module.exports = function(fastify, opts, next) {
  const authHandler = require('../handlers/auth')(fastify)
  fastify.get('/', authHandler.getRoot)
  next()
}

handler/auth:

module.exports = function (fastify) {
  getRoot: (request, reply) {
    fastify;
    reply.code(204).send({
      type: 'warning',
      message: 'No content'
    })
  }
}

1
  • My savior! <3 Thanks!
    – HypeWolf
    Nov 13, 2018 at 19:12
1

This was added by default

module.exports = { getRoot: (request, reply) {
// ACCESS FASTIFY NAMESPACE HERE
const fastify = request.server; 
/* The Fastify server instance, scoped to the current encapsulation context */
reply.code(204).send({
  type: 'warning',
  message: 'No content'
})}}

Ref : https://www.fastify.io/docs/latest/Reference/Request/

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.