Fastify core concepts
Second chapter of the "Fastify with TypeScript" series. Before jumping into project setup, let's build a mental map of how Fastify is actually put together. Everything you'll build in the rest of this series — routes, plugins, authentication, database access — is a combination of five core building blocks, and every later chapter is really just a deep dive into one of them.
We'll go through the five ideas first, then run one small file that uses all of them.
1. The Fastify instance
Everything starts from a single call to Fastify(), which returns an instance exposing a small API: .get(), .post(), .register(), .decorate(), .addHook(), and so on.
const app = Fastify({ logger: true }); That instance is passed down through every plugin you register, which is why so much of Fastify's API is designed around receiving fastify as a function parameter rather than importing a global singleton — this is what makes testing and dependency injection so natural.
2. Plugins and encapsulation
Plugins are Fastify's unit of composition. Anything — a route, a set of routes, a database connection, an auth check — can be wrapped in a plugin and registered with app.register().
What makes this powerful is encapsulation: by default, the decorators and hooks a plugin declares only apply inside that plugin and its children, not to its siblings or its parent. This lets you scope behavior — like "every route under /admin requires an admin JWT" — without leaking it to the rest of the app. When you do want something to be visible everywhere (like a database connection), you wrap the plugin with fastify-plugin to opt out of encapsulation. (Chapter 8)
3. The request/reply lifecycle and hooks
Every incoming request flows through a well-defined sequence of stages — parsing, validation, your handler, serialization, and so on — and Fastify lets you hook into each one (onRequest, preValidation, preHandler, onSend, etc.). This is how cross-cutting concerns like authentication, logging, or response shaping get applied consistently without cluttering your route handlers. (Chapter 9)
4. Decorators
Decorators are how you extend the Fastify instance, the request, or the reply with your own properties and methods — a database client on app.pg, a request.user populated by an auth hook, a custom reply.sendError() helper. They follow the same encapsulation rules as everything else in a plugin, and in TypeScript they're made fully type-safe through module augmentation. (Chapter 11)
5. Schema-based validation and serialization
Instead of validating input manually inside handlers, you attach a JSON Schema (or a TypeBox schema, which is just a nicer way to write one) directly to a route. Fastify validates incoming requests against it, and uses the response schema to serialize the reply at high speed. As a side effect, any field not declared in the response schema is stripped out, which is a great safety net against leaking sensitive data. (Chapter 7)
All five in one file
In the hello-fastify folder from the previous chapter, create concepts.ts:
// concepts.ts import Fastify from 'fastify'; declare module 'fastify' { interface FastifyInstance { greet: (name: string) => string; // tells TypeScript about the decorator below } } // 1. The instance const app = Fastify({ logger: true }); // 2. A plugin: what is declared inside stays inside app.register(async function greetings(fastify) { // 4. A decorator: a new method on the instance fastify.decorate('greet', (name: string) => `Hello, ${name}!`); // 3. A hook: runs for every request handled by this plugin fastify.addHook('onRequest', async (request) => { request.log.info('greetings hook'); }); // 5. A schema: validates the input and shapes the output fastify.get('/hello/:name', { schema: { params: { type: 'object', properties: { name: { type: 'string', maxLength: 10 } }, required: ['name'], }, response: { 200: { type: 'object', properties: { message: { type: 'string' } } }, }, }, }, async (request) => { const { name } = request.params as { name: string }; return { message: fastify.greet(name), internal: 'never leaves the server' }; }); }); // Outside the plugin: no hook runs here, and app.greet does not exist app.get('/ping', async () => ({ pong: true, hasGreet: app.hasDecorator('greet') })); await app.listen({ port: 3000 }); Start it with node concepts.ts and, from another terminal, make three requests. Each one shows a different building block at work.
curl localhost:3000/hello/world # {"message":"Hello, world!"} The handler returned two fields, but only message came back: internal isn't in the response schema, so Fastify dropped it. In the server log you'll also find a greetings hook line, written by the hook before the handler ran.
curl localhost:3000/hello/averyveryverylongname # {"statusCode":400,"code":"FST_ERR_VALIDATION","error":"Bad Request","message":"params/name must NOT have more than 10 characters"} The name is longer than the schema allows, so Fastify answered 400 on its own. The handler never ran, and we wrote no validation code.
curl localhost:3000/ping # {"pong":true,"hasGreet":false} This route lives outside the plugin, and that's encapsulation: no greetings hook line appears in the log for this request, and hasGreet is false because the decorator only exists inside greetings.
Don't worry about the details yet (the declare module block, the as cast, the shape of the schema): each has its own chapter. What matters now is the picture: a request enters the instance, is routed into a plugin, passes through its hooks, is checked against a schema, reaches a handler that can use decorators, and is serialized back out through the response schema.
Keep this mental model in mind as we go.
⬅️ Previous chapter: Introduction to Fastify · ➡️ Next chapter: Project setup
This article is part of the "Fastify with TypeScript" series — chapter 2 of 18.


