Building APIs with Fastify

Build fast, schema-driven Node.js APIs with Fastify's plugin system, built-in validation and structured logging.

Intermediate · about 10 hours · difficulty 3/5

Learn first: Node.js Runtime Essentials, REST API Design

Fastify is a modern alternative to Express that is faster, has first-class TypeScript support and builds validation and logging into the framework.

What is different

  • Schemas on routes: declare JSON schemas (or use a Zod type provider) for body, params and response. Fastify validates input and serialises output quickly, and strips fields you did not declare.
  • Plugins and encapsulation: features register as plugins with their own routes, hooks and decorators, which keeps large apps organised.
  • Hooks such as onRequest and preHandler replace most Express middleware.
  • Logging with Pino is built in, producing structured JSON logs.

When to choose it

Pick Fastify for performance-sensitive APIs, for teams who like schema-first design, or when you want response serialisation to guarantee private fields never leak. The concepts (routing, auth, errors, layering) are the same as Express.

Pitfalls

  • Trying to use Express middleware directly; you need the compatibility plugin or a Fastify-native equivalent.
  • Ignoring encapsulation and registering decorators where other plugins cannot see them.
  • Not defining response schemas, missing one of Fastify's main benefits.

You are ready to move on when you have a Fastify API with plugin-based feature modules, schema validation on every route, and response schemas that hide internal fields.

Key concepts

  • Routes with schemas
  • Plugins and encapsulation
  • Hooks
  • Zod type provider
  • Response serialisation
  • Built-in Pino logging

Other options for this step

Mini project

Build the placement portal API in Fastify with plugins for companies and applications, request and response schemas, an auth hook and structured logs.

Check yourself

How can a Fastify response schema prevent a passwordHash field from ever reaching the client?

Free resources