Hooks

Hooks are registered with the fastify.addHook method and allow you to listen to specific events in the application or request/response lifecycle. You have to register a hook before the event is triggered, otherwise the event is lost.

By using hooks you can interact directly with the lifecycle of Fastify. There are Request/Reply hooks and application hooks:

Notice: the done callback is not available when using async/await or returning a Promise. If you do invoke a done callback in this situation unexpected behaviour may occur, e.g. duplicate invocation of handlers.

Request/Reply Hooks

Request and Reply are the core Fastify objects.done is the function to continue with the lifecycle.

It is pretty easy to understand where each hook is executed by looking at the lifecycle page.Hooks are affected by Fastify's encapsulation, and can thus be applied to selected routes. See the Scopes section for more information.

There are eight different hooks that you can use in Request/Reply (in order of execution):

onRequest

  1. fastify.addHook('onRequest', (request, reply, done) => {
  2. // Some code
  3. done()
  4. })

Or async/await:

  1. fastify.addHook('onRequest', async (request, reply) => {
  2. // Some code
  3. await asyncMethod()
  4. return
  5. })

Notice: in the onRequest hook, request.body will always be null, because the body parsing happens before the preValidation hook.

preParsing

  1. fastify.addHook('preParsing', (request, reply, done) => {
  2. // Some code
  3. done()
  4. })

Or async/await:

  1. fastify.addHook('preParsing', async (request, reply) => {
  2. // Some code
  3. await asyncMethod()
  4. return
  5. })

Notice: in the preParsing hook, request.body will always be null, because the body parsing happens before the preValidation hook.

preValidation

  1. fastify.addHook('preValidation', (request, reply, done) => {
  2. // Some code
  3. done()
  4. })

Or async/await:

  1. fastify.addHook('preValidation', async (request, reply) => {
  2. // Some code
  3. await asyncMethod()
  4. return
  5. })

preHandler

  1. fastify.addHook('preHandler', (request, reply, done) => {
  2. // some code
  3. done()
  4. })

Or async/await:

  1. fastify.addHook('preHandler', async (request, reply) => {
  2. // Some code
  3. await asyncMethod()
  4. return
  5. })

preSerialization

If you are using the preSerialization hook, you can change (or replace) the payload before it is serialized. For example:

  1. fastify.addHook('preSerialization', (request, reply, payload, done) => {
  2. const err = null;
  3. const newPayload = { wrapped: payload }
  4. done(err, newPayload)
  5. })

Or async/await

  1. fastify.addHook('preSerialization', async (request, reply, payload) => {
  2. return { wrapped: payload }
  3. })

Note: the hook is NOT called if the payload is a string, a Buffer, a stream or null.

onError

  1. fastify.addHook('onError', (request, reply, error, done) => {
  2. // Some code
  3. done()
  4. })

Or async/await:

  1. fastify.addHook('onError', async (request, reply, error) => {
  2. // Useful for custom error logging
  3. // You should not use this hook to update the error
  4. })

This hook is useful if you need to do some custom error logging or add some specific header in case of error.It is not intended for changing the error, and calling reply.send will throw an exception.This hook will be executed only after the customErrorHandler has been executed, and only if the customErrorHandler sends an error back to the user (Note that the default customErrorHandler always sends the error back to the user).Notice: unlike the other hooks, pass an error to the done function is not supported.

onSend

If you are using the onSend hook, you can change the payload. For example:

  1. fastify.addHook('onSend', (request, reply, payload, done) => {
  2. const err = null;
  3. const newPayload = payload.replace('some-text', 'some-new-text')
  4. done(err, newPayload)
  5. })

Or async/await:

  1. fastify.addHook('onSend', async (request, reply, payload) => {
  2. const newPayload = payload.replace('some-text', 'some-new-text')
  3. return newPayload
  4. })

You can also clear the payload to send a response with an empty body by replacing the payload with null:

  1. fastify.addHook('onSend', (request, reply, payload, done) => {
  2. reply.code(304)
  3. const newPayload = null
  4. done(null, newPayload)
  5. })

You can also send an empty body by replacing the payload with the empty string '', but be aware that this will cause the Content-Length header to be set to 0, whereas the Content-Length header will not be set if the payload is null.

Note: If you change the payload, you may only change it to a string, a Buffer, a stream, or null.

onResponse

  1. fastify.addHook('onResponse', (request, reply, done) => {
  2. // Some code
  3. done()
  4. })

Or async/await:

  1. fastify.addHook('onResponse', async (request, reply) => {
  2. // Some code
  3. await asyncMethod()
  4. return
  5. })

The onResponse hook is executed when a response has been sent, so you will not be able to send more data to the client. It can however be useful for sending data to external services, for example to gather statistics.

Manage Errors from a hook

If you get an error during the execution of your hook, just pass it to done() and Fastify will automatically close the request and send the appropriate error code to the user.

  1. fastify.addHook('onRequest', (request, reply, done) => {
  2. done(new Error('Some error'))
  3. })

If you want to pass a custom error code to the user, just use reply.code():

  1. fastify.addHook('preHandler', (request, reply, done) => {
  2. reply.code(400)
  3. done(new Error('Some error'))
  4. })

The error will be handled by Reply.

Respond to a request from a hook

If needed, you can respond to a request before you reach the route handler, for example when implementing an authentication hook. Replying from an hook implies that the hook chain is stopped and the rest of hooks and the handlers are not executed. If the hook is using the callback approach, i.e. it is not an async function or it returns a Promise, it is as simple as calling reply.send() and avoiding calling the callback. If the hook is async, reply.send() must be called before the function returns or the promise resolves, otherwise the request will proceed. When reply.send() is called outside of the promise chain, it is important to return reply otherwise the request will be executed twice.

It is important to not mix callbacks and async/Promise, otherwise the hook chain will be executed twice.

If you are using onRequest or preHandler use reply.send; if you are using a middleware, use res.end.

  1. fastify.addHook('onRequest', (request, reply, done) => {
  2. reply.send('Early response')
  3. })
  4. // Works with async functions too
  5. fastify.addHook('preHandler', async (request, reply) => {
  6. await something()
  7. reply.send({ hello: 'world' })
  8. return reply // optional in this case, but it is a good practice
  9. })

If you want to respond with a stream, you should avoid using an async function for the hook. If you must use an async function, your code will need to follow the pattern in test/hooks-async.js.

  1. fastify.addHook('onRequest', (request, reply, done) => {
  2. const stream = fs.createReadStream('some-file', 'utf8')
  3. reply.send(stream)
  4. })

If you are sending a response without await on it, make sure to always return reply:

  1. fastify.addHook('preHandler', async (request, reply) => {
  2. setImmediate(() => { reply.send('hello') })
  3. // This is needed to signal the handler to wait for a response
  4. // to be sent outside of the promise chain
  5. return reply
  6. })
  7. fastify.addHook('preHandler', async (request, reply) => {
  8. // the fastify-static plugin will send a file asynchronously,
  9. // so we should return reply
  10. reply.sendFile('myfile')
  11. return reply
  12. })

Application Hooks

You can hook into the application-lifecycle as well. It's important to note that these hooks aren't fully encapsulated. The this inside the hooks are encapsulated but the handlers can respond to an event outside the encapsulation boundaries.

onClose

Triggered when fastify.close() is invoked to stop the server. It is useful when plugins need a "shutdown" event, for example to close an open connection to a database.The first argument is the Fastify instance, the second one the done callback.

  1. fastify.addHook('onClose', (instance, done) => {
  2. // Some code
  3. done()
  4. })

onRoute

Triggered when a new route is registered. Listeners are passed a routeOptions object as the sole parameter. The interface is synchronous, and, as such, the listeners do not get passed a callback.

  1. fastify.addHook('onRoute', (routeOptions) => {
  2. //Some code
  3. routeOptions.method
  4. routeOptions.schema
  5. routeOptions.url
  6. routeOptions.bodyLimit
  7. routeOptions.logLevel
  8. routeOptions.logSerializers
  9. routeOptions.prefix
  10. })

If you are authoring a plugin and you need to customize application routes, like modifying the options or adding new route hooks, this is the right place.

  1. fastify.addHook('onRoute', (routeOptions) => {
  2. function onPreSerialization(request, reply, payload, done) {
  3. // Your code
  4. done(null, payload)
  5. }
  6. // preSerialization can be an array or undefined
  7. routeOptions.preSerialization = [...(routeOptions.preSerialization || []), onPreSerialization]
  8. })

onRegister

Triggered when a new plugin is registered and a new encapsulation context is created. The hook will be executed before the registered code.This hook can be useful if you are developing a plugin that needs to know when a plugin context is formed, and you want to operate in that specific context.Note: This hook will not be called if a plugin is wrapped inside fastify-plugin.

  1. fastify.decorate('data', [])
  2. fastify.register(async (instance, opts) => {
  3. instance.data.push('hello')
  4. console.log(instance.data) // ['hello']
  5. instance.register(async (instance, opts) => {
  6. instance.data.push('world')
  7. console.log(instance.data) // ['hello', 'world']
  8. }, { prefix: '/hola' })
  9. }, { prefix: '/ciao' })
  10. fastify.register(async (instance, opts) => {
  11. console.log(instance.data) // []
  12. }, { prefix: '/hello' })
  13. fastify.addHook('onRegister', (instance, opts) => {
  14. // Create a new array from the old one
  15. // but without keeping the reference
  16. // allowing the user to have encapsulated
  17. // instances of the `data` property
  18. instance.data = instance.data.slice()
  19. // the options of the new registered instance
  20. console.log(opts.prefix)
  21. })

Scope

Except for Application Hooks, all hooks are encapsulated. This means that you can decide where your hooks should run by using register as explained in the plugins guide. If you pass a function, that function is bound to the right Fastify context and from there you have full access to the Fastify API.

  1. fastify.addHook('onRequest', function (request, reply, done) {
  2. const self = this // Fastify context
  3. done()
  4. })

Note: using an arrow function will break the binding of this to the Fastify instance.

Route level hooks

You can declare one or more custom onRequest, onReponse, preParsing, preValidation, preHandler and preSerialization hook(s) that will be unique for the route. If you do so, those hooks are always executed as the last hook in their category.This can be useful if you need to implement authentication, where the preParsing or preValidation hooks are exactly what you need. Multiple route-level hooks can also be specified as an array.

  1. fastify.addHook('onRequest', (request, reply, done) => {
  2. // Your code
  3. done()
  4. })
  5. fastify.addHook('onResponse', (request, reply, done) => {
  6. // your code
  7. done()
  8. })
  9. fastify.addHook('preParsing', (request, reply, done) => {
  10. // Your code
  11. done()
  12. })
  13. fastify.addHook('preValidation', (request, reply, done) => {
  14. // Your code
  15. done()
  16. })
  17. fastify.addHook('preHandler', (request, reply, done) => {
  18. // Your code
  19. done()
  20. })
  21. fastify.addHook('preSerialization', (request, reply, payload, done) => {
  22. // Your code
  23. done(null, payload)
  24. })
  25. fastify.route({
  26. method: 'GET',
  27. url: '/',
  28. schema: { ... },
  29. onRequest: function (request, reply, done) {
  30. // This hook will always be executed after the shared `onRequest` hooks
  31. done()
  32. },
  33. onResponse: function (request, reply, done) {
  34. // this hook will always be executed after the shared `onResponse` hooks
  35. done()
  36. },
  37. preParsing: function (request, reply, done) {
  38. // This hook will always be executed after the shared `preParsing` hooks
  39. done()
  40. },
  41. preValidation: function (request, reply, done) {
  42. // This hook will always be executed after the shared `preValidation` hooks
  43. done()
  44. },
  45. preHandler: function (request, reply, done) {
  46. // This hook will always be executed after the shared `preHandler` hooks
  47. done()
  48. },
  49. // // Example with an array. All hooks support this syntax.
  50. //
  51. // preHandler: [function (request, reply, done) {
  52. // // This hook will always be executed after the shared `preHandler` hooks
  53. // done()
  54. // }],
  55. preSerialization: (request, reply, payload, done) => {
  56. // This hook will always be executed after the shared `preSerialization` hooks
  57. done(null, payload)
  58. },
  59. handler: function (request, reply) {
  60. reply.send({ hello: 'world' })
  61. }
  62. })

Note: both options also accept an array of functions.