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
fastifyinpackage.json, often with@fastify/autoloadfastify.register(...),fastify.decorate(...)andfastify.addHook(...)- Route definitions with a
schemaobject
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-pluginto 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
- The app file, to see the plugin registration tree
src/plugins/, for what is decorated onto the instance- The route file and its schema
How a request moves through the code
onRequesthooks run (often authentication).- The body is parsed and validated against the route schema; invalid input returns 400 automatically.
preHandlerhooks run, then the route handler.- The reply is serialised using the response schema.
onSendandonResponsehooks 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-pluginis 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.