Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 39 ยท Hooks and Lifecycle

Request and Reply Hooks in Practice

Use Fastify request and reply hooks the right way: timing, request IDs, route-level hooks, response envelopes, headers in onSend, and how plugin scope limits hooks.

You know the order of the hooks. Now it is time to use them. This lesson builds five small, realistic features out of request and reply hooks: a request timer, a correlation ID header, a "load the record or 404" step, a response envelope, and a per-scope audit log. Each one fits a particular stage, and together they show why Fastify code stays flat: cross-cutting work lives in hooks, and handlers hold only business logic.

Examples use the stand-in framework from The Fastify Request Lifecycle (the real package is not installed here). The hook signatures match real Fastify: async (request, reply) for request hooks and async (request, reply, payload) for preSerialization and onSend.

Match the job to the hook

Timing Start in onRequest, finish in onResponse.
Request ID Set a header in onSend.
Load record preHandler, after validation.
Envelope preSerialization wraps the object.

Handlers stay small when hooks do the rest.

1 / 2

Timing and correlation IDs

A timer needs two hook calls that share data. The place to share data between hooks is the request object, but only if you declare the property first. Real Fastify calls this decorating the request: app.decorateRequest('startedAt', 0) reserves the property so every request object has the same shape. That keeps objects monomorphic, which V8 optimizes well, and it avoids surprises when a plugin writes the same name.

Node.js Timer and request-id header

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.

Two notes. First, an onSend hook that changes headers must still return the payload (or undefined to keep it unchanged in this stand-in; real Fastify expects you to return the payload when you use the promise style, so returning it is the safe habit). Second, onResponse runs after the response is sent, so the time you measure there includes serialization and sending, which is what a client experiences.

Real Fastify already assigns request.id (req-1, req-2, ...) and logs it. You can override it with the genReqId option or reuse a header such as x-request-id from a gateway, so one ID follows a request through all your services.

Load the record, or answer 404

A very common pattern: three routes need the same lookup (GET, PUT and DELETE on /notes/:id). Copy-pasting findNote and the 404 branch into each handler is noisy. A preHandler does it once and stores the result on the request. It must run after validation (so :id has been checked) and before the handler.

Route-level hooks are given as options on the route and run after the app-level hooks of the same stage.

Node.js A preHandler that loads the note

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.

The schema turns "1" into the integer 1 before loadNote runs (the Map is keyed by number). /notes/abc fails validation with a 400, so the hook is never called: this is the point of ordering preHandler after validation. The handlers are now one or two lines each.

Wrapping responses with preSerialization

preSerialization receives the object your handler returned and may return a different one. It is the right place for an envelope such as { data: ..., meta: ... }, for renaming fields, or for stripping internal ones. It is not called for strings and buffers, because those are already final bytes.

JavaScript
// real Fastify: wrap every successful JSON response
app.addHook('preSerialization', async (request, reply, payload) => {
  if (reply.statusCode >= 400) return payload;      // leave error bodies alone
  return { data: payload, requestId: request.id };
});

Use envelopes only when you have decided that all clients get them. Mixing wrapped and unwrapped responses is a bug waiting to be found. Also remember the order: preSerialization runs before the response schema serializer, so the shape you return must still match the response schema, or the schema must describe the envelope.

Scope: hooks follow the plugin tree

A hook added with app.addHook applies to the instance it is called on and to all child plugins registered after it, but not to the parent or siblings. This is encapsulation applied to hooks, and it lets you restrict behavior to a group of routes without any if (url.startsWith(...)) checks.

Node.js Audit log only for the admin plugin

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.

Only the two admin calls are audited. If you want a hook to cover the whole app, add it on the root instance, or wrap it in fastify-plugin so it escapes the child scope.

Mistakes to avoid

  • Mixing async and done. An async hook must not take or call done.
  • Forgetting to return the payload in onSend/preSerialization when you use the promise style and mean to keep it.
  • Sending a reply and carrying on. After reply.send() in a hook, return from the hook; in real Fastify, return reply from async hooks so the framework knows the reply is complete.
  • Doing slow work in onRequest for every request, such as a database lookup, when only a few routes need it. Use a route-level preHandler for that.
  • Heavy work in onResponse. It does not delay the client, but it does occupy the event loop. Push slow logging to a queue.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which hook is the best place to load a record by :id so it can be reused by the handler?

    preHandler runs after validation, so the params are trusted, and right before the handler. onRequest runs before validation.
  2. 2. Why call decorateRequest('note', null) before assigning request.note in a hook?

    Declaring the property up front keeps request objects the same shape (faster for V8) and prevents two plugins from silently reusing the same name.
  3. 3. A hook added inside a plugin registered with a prefix applies to:

    Hooks are encapsulated. They affect the instance they were added to and its children, not the parent or siblings.
  4. 4. preSerialization is NOT called for which kind of payload?

    Strings and Buffers are already final, so there is nothing to serialize. The hook only sees values that still need JSON serialization.

Summary

  • Put cross-cutting work in hooks: timers in onRequest/onResponse, headers in onSend, loaders in preHandler, envelopes in preSerialization.
  • Declare request properties with decorateRequest before writing to them.
  • Route-level hooks (preHandler: fn) run after app-level hooks of the same stage.
  • A hook is scoped to its plugin and children; use the root instance or fastify-plugin for app-wide hooks.
  • Return the payload from onSend and preSerialization, never mix async and done, and keep onResponse cheap.

Next: Error Handling and Not Found Routes