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!

HypeWolf
  • 750
  • 12
  • 29

4 Answers4

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.

zenijos10
  • 205
  • 3
  • 8
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'
    });
  }
};
Milad ABC
  • 337
  • 1
  • 2
  • 13
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

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/

sundar.sat84
  • 489
  • 4
  • 11