Skip to content

Fastify

Francois edited this page Jan 4, 2026 · 2 revisions

Fastify

Fastify is a web framework for Node.js

Key advantages for our project are

  • performance : handles up to 30 000 requests per second
  • modularity : extensible via hooks, plugins, decorator
  • type safety : TS integration and built-in support for JSON schema validation

Setup

npm install fastify fastify-type-provider-zod zod
npm install --save-dev @types/node typescript

Plugins

Note

Fastify uses an encapsulation model. Plugins registered inside a context (scope) are not visible to parents or siblings unless wrapped with fastify-plugin.

Validating in routes with Zod

  • requires fastify-type-provider-zod

Tip

Use shared @transcendence/core shemas and DTOs to have single source of truth between exposed API and their consumers

Tip

Use fastify.printRoutes() in development to visualize your entire routing tree and debug 404 errors.

Do's & Don'ts

✅ Do ❌ Don't
Encapsulate plugins: Use fastify-plugin (or fp) to break encapsulation when registering shared plugins (Db, Auth) so they are available globally. Register every plugin without fastify-plugin; this isolates them to the current scope/file, often breaking dependency chains.
Use Zod Schemas: Define validation schemas for every route (body, querystring, params). Manually validate data inside the handler function (e.g., if (!req.body.name)...).
Use Hooks for Logic: Use onRequest or preHandler for authentication and logging. Put authentication logic directly inside every single route handler.
Await Plugins: Always use await fastify.register(...) to ensure plugins load in order. Forget await during registration, which leads to race conditions at startup.
Throw Errors: Throw standard Error objects; Fastify catches them and sends 500 (or custom codes). Send manual 500 responses (res.code(500).send(...)) for unexpected crashes; let the framework handle it.

Resources

Type Resource Notes
📄 Fastify Documentation Official Reference
📦 fastify-type-provider-zod Zod integration docs
🎥 Fastify Project structure -
💻 Awesome Fastify -

Clone this wiki locally