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.

Request/Response Hooks

By using the hooks you can interact directly inside the lifecycle of Fastify. There are seven different Hooks that you can use (in order of execution):

  • 'onRequest'
  • 'preParsing'
  • 'preValidation'
  • 'preHandler'
  • 'preSerialization'
  • 'onError'
  • 'onSend'
  • 'onResponse'Example:
  1. fastify.addHook('onRequest', (request, reply, done) => {
  2. // some code
  3. done()
  4. })
  5. fastify.addHook('preParsing', (request, reply, done) => {
  6. // some code
  7. done()
  8. })
  9. fastify.addHook('preValidation', (request, reply, done) => {
  10. // some code
  11. done()
  12. })
  13. fastify.addHook('preHandler', (request, reply, done) => {
  14. // some code
  15. done()
  16. })
  17. fastify.addHook('preSerialization', (request, reply, payload, done) => {
  18. // some code
  19. done()
  20. })
  21. fastify.addHook('onError', (request, reply, error, done) => {
  22. // some code
  23. done()
  24. })
  25. fastify.addHook('onSend', (request, reply, payload, done) => {
  26. // some code
  27. done()
  28. })
  29. fastify.addHook('onResponse', (request, reply, done) => {
  30. // some code
  31. done()
  32. })

Or async/await

  1. fastify.addHook('onRequest', async (request, reply) => {
  2. // some code
  3. await asyncMethod()
  4. // error occurred
  5. if (err) {
  6. throw new Error('some errors occurred.')
  7. }
  8. return
  9. })
  10. fastify.addHook('preParsing', async (request, reply) => {
  11. // some code
  12. await asyncMethod()
  13. // error occurred
  14. if (err) {
  15. throw new Error('some errors occurred.')
  16. }
  17. return
  18. })
  19. fastify.addHook('preValidation', async (request, reply) => {
  20. // some code
  21. await asyncMethod()
  22. // error occurred
  23. if (err) {
  24. throw new Error('some errors occurred.')
  25. }
  26. return
  27. })
  28. fastify.addHook('preHandler', async (request, reply) => {
  29. // some code
  30. await asyncMethod()
  31. // error occurred
  32. if (err) {
  33. throw new Error('some errors occurred.')
  34. }
  35. return
  36. })
  37. fastify.addHook('preSerialization', async (request, reply, payload) => {
  38. // some code
  39. await asyncMethod()
  40. // error occurred
  41. if (err) {
  42. throw new Error('some errors occurred.')
  43. }
  44. return payload
  45. })
  46. fastify.addHook('onError', async (request, reply, error) => {
  47. // useful for custom error logging
  48. // you should not use this hook to update the error
  49. })
  50. fastify.addHook('onSend', async (request, reply, payload) => {
  51. // some code
  52. await asyncMethod()
  53. // error occurred
  54. if (err) {
  55. throw new Error('some errors occurred.')
  56. }
  57. return
  58. })
  59. fastify.addHook('onResponse', async (request, reply) => {
  60. // some code
  61. await asyncMethod()
  62. // error occurred
  63. if (err) {
  64. throw new Error('some errors occurred.')
  65. }
  66. return
  67. })

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 behavior may occur, e.g. duplicate invocation of handlers.

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

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.

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.

The onError Hook

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 back an error to the user (Note that the default customErrorHandler always send back the error to the user).Notice: unlike the other hooks, pass an error to the done function is not supported.

  1. fastify.addHook('onError', (request, reply, error, done) => {
  2. // apm stands for Application Performance Monitoring
  3. apm.sendError(error)
  4. done()
  5. })
  6. // Or async
  7. fastify.addHook('onError', async (request, reply, error) => {
  8. // apm stands for Application Performance Monitoring
  9. apm.sendError(error)
  10. })

The preSerialization Hook

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. var err = null;
  3. var newPayload = {wrapped: payload }
  4. done(err, newPayload)
  5. })
  6. // Or async
  7. fastify.addHook('preSerialization', async (request, reply, payload) => {
  8. return {wrapped: payload }
  9. })

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

The onSend Hook

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

  1. fastify.addHook('onSend', (request, reply, payload, done) => {
  2. var err = null;
  3. var newPayload = payload.replace('some-text', 'some-new-text')
  4. done(err, newPayload)
  5. })
  6. // Or async
  7. fastify.addHook('onSend', async (request, reply, payload) => {
  8. var newPayload = payload.replace('some-text', 'some-new-text')
  9. return newPayload
  10. })

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.

The onResponse Hook

The onResponse hook is executed when a response has been sent, so you will not be able to send more data to the client, however you can use this hook to send some data to an external service or elaborate some statistics.

Respond to a request from a hook

If needed, you can respond to a request before you reach the route handler. An example could be an authentication hook. If you are using onRequest or preHandler use reply.send; if you are using a middleware, 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. reply.send({ hello: 'world' })
  7. })

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

Application Hooks

You are able to 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'
  • 'onRoute'
  • 'onRegister''onClose'Triggered when fastify.close() is invoked to stop the server. It is useful when plugins need a "shutdown" event, such as a 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.prefix
  9. })

'onRegister'Triggered when a new plugin function is registered, and a new encapsulation context is created, the hook will be executed before the plugin 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. })
  9. })
  10. fastify.register(async (instance, opts) => {
  11. console.log(instance.data) // []
  12. })
  13. fastify.addHook('onRegister', (instance) => {
  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. })

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, preParsing, preValidation, preHandler and preSerialization hook(s) that will be unique for the route. If you do so, those hooks always be executed as last hook in their category.This can be useful if you need to run the authentication, and the preParsing or preValidation hooks are exactly what you need for doing that. Multiple route-level hooks can also be specified as an array.

Let's make an example:

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

Note: both options also accept an array of functions.