Lifecycle

Following the schema of the internal lifecycle of Fastify.
On the right branch of every section there is the next phase of the lifecycle, on the left branch there is the corresponding error code that will be generated if the parent throws an error (note that all the errors are automatically handled by Fastify).

  1. Incoming Request
  2. └─▶ Routing
  3. └─▶ Instance Logger
  4. 4**/5** ◀─┴─▶ onRequest Hook
  5. 4**/5** ◀─┴─▶ preParsing Hook
  6. 4**/5** ◀─┴─▶ Parsing
  7. 4**/5** ◀─┴─▶ preValidation Hook
  8. 415 ◀─┴─▶ Validation
  9. 4**/5** ◀─┴─▶ preHandler Hook
  10. 4**/5** ◀─┴─▶ User Handler
  11. └─▶ Reply
  12. 4**/5** ◀─┴─▶ preSerialization Hook
  13. └─▶ onSend Hook
  14. 4**/5** ◀─┴─▶ Outgoing Response
  15. └─▶ onResponse Hook

At any point before or during the User Handler, reply.hijack() can be called to prevent Fastify from:

  • Running all the following hooks and user handler
  • Sending the response automatically

NB (*): If reply.raw is used to send a response back to the user, onResponse hooks will still be executed

Reply Lifecycle

Whenever the user handles the request, the result may be:

  • in async handler: it returns a payload
  • in async handler: it throws an Error
  • in sync handler: it sends a payload
  • in sync handler: it sends an Error instance

If the reply was hijacked, we skip all the below steps. Otherwise, when it is being submitted, the data flow performed is the following:

  1. schema validation Error
  2. └─▶ schemaErrorFormatter
  3. reply sent ◀── JSON ─┴─ Error instance
  4. throw an Error
  5. send or return
  6. reply sent ◀── JSON ─┴─ Error instance ──▶ setErrorHandler ◀─────┘
  7. reply sent ◀── JSON ─┴─ Error instance ──▶ onError Hook
  8. └─▶ reply sent

Note: reply sent means that the JSON payload will be serialized by: