Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 39 ยท Getting Started

How a Request Flows Through Fastify

Understand the Fastify request lifecycle and its core objects: the instance, request, reply, hooks, decorators and plugins, with runnable examples of the order.

Before you write many routes, it pays to understand the path every request takes through Fastify. Once you know the order of the steps, hooks, validation and error handling stop feeling like magic. This lesson gives you the map; later chapters walk each stop in detail.

Four objects appear everywhere: the instance (the app you created), the request, the reply and the plugin context. You will meet them again in nearly every lesson.

The four core objects

Object What it is Where you see it
Instance The server object: routes, hooks, decorators, plugins const app = Fastify()
Request Everything about the incoming call: params, query, body, headers, id, log First argument of a handler
Reply How you answer: code(), header(), type(), send() Second argument of a handler
Plugin context A child instance with its own scope The function you pass to app.register()

An instance holds a tree of child instances (one per plugin). A request is handled in the scope of the instance where its route was defined, and that scope decides which hooks, decorators and error handlers apply. This is encapsulation, covered in chapter 4.

The lifecycle

Every request goes through the same fixed sequence. Hooks let you run code at each step.

flowchart TD
    A["Incoming request"] --> B["Routing: find the route"]
    B --> C["onRequest hooks"]
    C --> D["preParsing hooks"]
    D --> E["Body parsing"]
    E --> F["preValidation hooks"]
    F --> G["Validation (schema)"]
    G --> H["preHandler hooks"]
    H --> I["Your handler"]
    I --> J["preSerialization hooks"]
    J --> K["onSend hooks"]
    K --> L["Response sent"]
    L --> M["onResponse hooks"]

The lifecycle in order. If a step throws or sends a reply, the rest of the normal path is skipped and the error handler runs.

Notes on the diagram:

  • Routing comes first. If no route matches, the not-found handler answers.
  • Body parsing happens only for methods that carry a body (POST, PUT, PATCH, ...). Fastify parses JSON and plain text out of the box.
  • Validation runs only if the route has a schema. It uses the already parsed body, querystring, params and headers.
  • preSerialization runs only when the payload is an object that will be turned into JSON.
  • onSend can still change the payload as a string or buffer; after it, bytes go out.
  • onResponse runs after the response has been written; use it for metrics and cleanup, never to change the reply.

The stand-in implements these steps (except preParsing), so you can watch the order.

Node.js Watch the lifecycle order

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.

In real Fastify you can also write hooks with a done callback ((request, reply, done) => { ...; done(); }). In async hooks you simply return or await, and you must not mix async with done. This course uses the async style.

Short-circuiting the lifecycle

A hook can end a request early by sending a reply. This is how authentication works: an onRequest or preHandler hook checks a header and answers 401 before the handler ever runs.

In an async hook, await reply.code(401).send(...) stops the chain; in the stand-in (and in real Fastify) you should return the reply so Fastify knows the response is on its way.

Node.js A hook that stops the request

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.

Hooks added with app.addHook apply to all routes of that instance and its children. Hooks defined inside a plugin apply only inside that plugin. Route-level hooks (preHandler in the route options) apply to one route. Chapter 5 of this course studies hooks in depth.

Decorators in one minute

Instances, requests and replies are ordinary objects, but adding properties to them freely would slow Fastify down and hide bugs. Instead, you add your own with decorators:

JavaScript
app.decorate('config', { appName: 'Demo' });        // app.config
app.decorateRequest('user', null);                  // request.user
app.decorateReply('notFoundJson', function () {     // reply.notFoundJson()
  return this.code(404).send({ error: 'nope' });
});

Declaring the property up front lets Fastify keep objects the same "shape", which keeps them fast, and it stops two plugins from silently overwriting each other. The decorators lesson covers them fully.

Errors in the lifecycle

If a hook, the validation step or your handler throws (or returns a rejected promise), Fastify skips ahead to the error handler and sends an error response. By default that response has this shape:

JSON
{ "statusCode": 500, "error": "Internal Server Error", "message": "something broke" }

You can customize it with setErrorHandler, per instance. The async handlers lesson goes deeper.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In which order do these steps run?

    onRequest runs first, then preHandler, then your handler, then onSend before the response goes out.
  2. 2. What does the validation step use to decide what to check?

    Validation runs only for routes that define a schema for body, querystring, params or headers.
  3. 3. How can a hook end a request before the handler runs?

    Sending a reply in a hook (for example a 401) short-circuits the lifecycle.
  4. 4. Why are decorators preferred over setting arbitrary properties on request or reply?

    Declared decorators keep objects fast and detect duplicate names.
  5. 5. When does onResponse run?

    onResponse runs after the reply is written; it is for metrics and cleanup, not for changing the reply.

Summary

  • The core objects are the instance, request, reply and plugin context.
  • Requests flow: routing, onRequest, parsing, preValidation, validation, preHandler, handler, preSerialization, onSend, response, onResponse.
  • Sending a reply from a hook ends the request early; thrown errors jump to the error handler.
  • Hooks and decorators are scoped to the instance (and its children) where you add them.
  • Decorators are the safe way to extend the instance, request and reply.

Next: Server Options and Logging