Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 39 ยท Hooks and Lifecycle

The Fastify Request Lifecycle

Follow one request through Fastify from routing to onResponse: every stage, what runs in it, how errors and early replies change the path, with runnable examples.

Every Fastify request travels the same road, in the same order, every time. Routing picks a handler, then a fixed series of stages runs: onRequest, preParsing, parsing, preValidation, validation, preHandler, your handler, preSerialization, onSend, and finally onResponse. Once you know this road you know where each piece of code belongs: authentication, body transformation, logging, response shaping.

The road is also the reason Fastify is predictable. Nothing runs "sometimes". If a plugin adds a hook, you can name the exact stage where it will fire and what data exists at that moment. This lesson draws the map and then lets you watch a request walk it.

The real Fastify package is not installed on this site (no npm). The examples use a small stand-in written for these lessons: fastify(), addHook, register, decorate, inject, reply.send and the lifecycle below behave like the real thing for what is shown, but it is about 120 lines, not the real framework. Real Fastify code appears in read-only blocks. Wherever a stand-in prints something, the real framework prints the same for these cases.

Before your handler

onRequest Headers and URL only. Auth lives here.
preParsing Raw body stream, before parsing.
Parsing Content-type parser builds request.body.
Validation preValidation, then schema checks.

Each stage can end the request early.

1 / 3

The full map

flowchart TD
  A["Incoming request"] --> B["Routing"]
  B --> C["onRequest"]
  C --> D["preParsing"]
  D --> E["Parsing"]
  E --> F["preValidation"]
  F --> G["Validation"]
  G --> H["preHandler"]
  H --> I["Handler"]
  I --> J["preSerialization"]
  J --> K["onSend"]
  K --> L["Response sent"]
  L --> M["onResponse"]
  C -. "reply.send() or error" .-> K
  G -. "validation error" .-> N["Error handler"]
  I -. "thrown error" .-> N
  N --> J

The dotted lines are shortcuts: an early reply or an error skips the middle stages but still passes through the stages after it.

Read it top to bottom as a pipeline:

Stage What exists at that moment Typical use
Routing Method and URL matched to a route Done for you
onRequest request.headers, request.query, request.params, no body yet Authentication, rate limits, request IDs
preParsing The raw payload stream Decompress or decrypt the incoming body
Parsing The content-type parser runs request.body is created (JSON, text, form)
preValidation request.body is parsed but unchecked Normalize input before the schema sees it
Validation Schemas for body, querystring, params, headers Reject bad input with a 400
preHandler Validated input Load a record, check ownership, per-route rules
Handler Everything above Business logic
preSerialization Payload as a JavaScript value Wrap or rename fields ({ data: ... })
onSend Payload as a string or Buffer Compress, sign, add headers
onResponse The response has been sent Logging, metrics, cleanup

Two words explain the naming. Hooks starting with pre run before the thing they name. on hooks react to an event. That is why preHandler runs just before your handler and onResponse runs after the response.

Watching a request walk the road

The first example adds one hook per stage and prints a line from each. The stand-in also accepts a trace function that reports the internal stages (parsing, validation, handler) that have no hook of their own.

Node.js One request, every stage

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice three things in the output. The -- stage lines and the hook: lines alternate, so you can see the hook for a stage fires when the stage starts. preSerialization sees an object but onSend sees a string, because serialization happened between them. And onResponse is last: the response is already on its way when it runs.

Shortcuts: early replies and errors

A hook can end the request. In an async hook you call reply.send(...) (and in real Fastify you also return reply, so the framework knows you answered). Everything between that stage and onSend is skipped. The handler never runs, which is exactly what you want for a rejected login or a cached response.

Errors do the same. If any stage throws, or validation fails, Fastify jumps to the error handler, builds an error response, and then continues with onSend and onResponse. The response still goes through the tail of the road, so a logging hook in onResponse sees failed requests too.

Node.js Early reply and validation failure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Case 2 never reaches parsing, validation or the handler. Case 3 never reaches preHandler, but both still reach onSend and onResponse. Try changing the header or the payload to see the path change.

Real Fastify: the same code, with a server

In real Fastify the code looks the same, except for listen:

JavaScript
import Fastify from 'fastify';

const app = Fastify({ logger: true });

app.addHook('onRequest', async (request, reply) => {
  request.log.info('a request arrived');
});

app.get('/ping', async () => ({ pong: true }));

await app.listen({ port: 3000, host: '0.0.0.0' });

Hooks come in two styles. The async style shown here returns a promise and never receives a done callback. The callback style has the signature (request, reply, done) and must call done(). Never mix them: an async function that also calls done can answer twice.

Choosing the right stage

A quick guide for where to put code:

  • Needs only headers or the URL? onRequest. It is the cheapest place to reject traffic, because nothing has been parsed yet.
  • Needs the body, but before validation? preValidation. For example, turn a string "5" into a number, or trim text fields.
  • Needs trusted, validated data? preHandler. Loading the user, checking permissions on a specific record.
  • Changes the response object? preSerialization. Changes the response bytes? onSend.
  • Observes the outcome? onResponse for timing and metrics. Do not try to change the response there; it is already gone.

Prefer an early stage over a late one when you reject something. Rejecting in onRequest costs a few microseconds; rejecting in preHandler costs parsing and validation first.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which hook runs first for every request?

    After routing, onRequest is the first hook. At that moment only the headers, URL, query and params are known; the body has not been read.
  2. 2. At which hook can you rely on request.body being parsed AND validated against the schema?

    preHandler runs after validation, so the body has passed its schema. preValidation sees the parsed but still unchecked body.
  3. 3. A hook sends a reply during onRequest. What happens to the handler?

    An early reply skips the middle stages including the handler. The response still passes through the final stages, so onSend and onResponse still see it.
  4. 4. What type is the payload in an onSend hook?

    Serialization happens between preSerialization and onSend. preSerialization still sees the object; onSend sees the serialized bytes.

Summary

  • Every request follows one fixed road: onRequest, preParsing, parsing, preValidation, validation, preHandler, handler, preSerialization, onSend, onResponse.
  • Choose the earliest stage that has the data you need; reject early to save work.
  • A reply sent inside a hook, or a thrown error, skips the middle of the road but not the end of it.
  • preSerialization works with objects, onSend with serialized payloads, and onResponse runs after the response left.
  • Use async hooks, and do not mix them with the done callback style.

Next: Application Hooks: onReady, onClose, onRoute