Skip to content

How to understand a Fastify codebase

Fastify is organised around plugins. Each `register` call creates an encapsulated context, so decorators and hooks added inside a plugin only apply to that plugin's routes unless it is wrapped with `fastify-plugin`. Routes usually declare JSON schemas that validate input and speed up output serialisation.

How to tell it's Fastify

  • fastify in package.json, often with @fastify/autoload
  • fastify.register(...), fastify.decorate(...) and fastify.addHook(...)
  • Route definitions with a schema object

Where things usually live

src/app.ts
Creates the instance and registers plugins and route folders.
src/plugins/
Shared plugins: database clients, auth, config. Often wrapped with fastify-plugin to be visible everywhere.
src/routes/
Route plugins; with autoload, the folder path becomes the URL prefix.
src/schemas/
Shared JSON schemas, often with TypeBox or Zod-to-JSON-schema.
src/server.ts
Calls listen.

Conventions, not rules. Real projects rename and move things, so confirm against the repository.

Where to start reading

  1. The app file, to see the plugin registration tree
  2. src/plugins/, for what is decorated onto the instance
  3. The route file and its schema

How a request moves through the code

  1. 1onRequest hooks run (often authentication).
  2. 2The body is parsed and validated against the route schema; invalid input returns 400 automatically.
  3. 3preHandler hooks run, then the route handler.
  4. 4The reply is serialised using the response schema.
  5. 5onSend and onResponse hooks run.

Questions to ask about the repository

  • Draw the plugin tree: which plugins are encapsulated and which are global?
  • Which decorators exist on the instance and request, and where are they added?
  • Which routes have no input schema?

What trips people up

  • A decorator added in an encapsulated plugin isn't visible to sibling plugins; fastify-plugin is the usual fix.
  • Response schemas drop properties that aren't declared, which can look like data loss.
  • Async handlers should return a value or call reply.send, not both.