Plugins and encapsulation
Eighth chapter of the "Fastify with TypeScript" series. The plugin system is arguably Fastify's most distinctive feature, and understanding encapsulation is essential to structuring any application well. We have been using a plugin since chapter 5 (userRoutes is one). In this chapter we write a second one, watch it fail in an instructive way, and fix it.
What a plugin is
A plugin is a function that receives a Fastify instance and adds things to it: routes, hooks, decorators, other plugins. You hand it to app.register().
The instance a plugin receives is not the root app. It is a child of it, and that is the whole point: what a plugin adds to its instance (hooks, decorators) exists inside that plugin and its own children, and nowhere else. This is encapsulation. Siblings don't see each other's hooks and decorators, and the parent doesn't see its children's.
A plugin of our own
buildApp() in src/app.ts is getting crowded, and the OpenAPI setup from the previous chapter has nothing to do with the rest of it. Let's move it into its own file. Create src/plugins/openapi.ts:
// src/plugins/openapi.ts import swagger from '@fastify/swagger'; import type { FastifyInstance } from 'fastify'; export default async function openapiPlugin(fastify: FastifyInstance) { // The OpenAPI document is generated from the route schemas await fastify.register(swagger, { openapi: { openapi: '3.1.0', info: { title: 'My Fastify App', version: '1.0.0' }, }, }); fastify.get('/openapi.json', { schema: { hide: true } }, async () => fastify.swagger()); } Then, in src/app.ts, replace the swagger import with:
import openapi from './plugins/openapi.ts'; and replace the app.register(swagger, ...) call and the /openapi.json route with:
// Must come before the routes: it collects them as they are declared app.register(openapi); It compiles, the server starts, and yet:
curl localhost:3000/openapi.json # {"openapi":"3.1.0","info":{"title":"My Fastify App","version":"1.0.0"},"components":{"schemas":{}},"paths":{}} paths is empty. Our routes are gone from the document.
Why it broke
@fastify/swagger works by adding a hook that is called every time a route is declared. Before, we registered it on the root app, so the hook saw every route. Now we register it inside openapiPlugin, so the hook lives in that plugin's own context. The users routes are declared in a sibling plugin, and siblings don't see each other's hooks. Nothing is wrong with the code: encapsulation is doing exactly what it promises.
Opting out with fastify-plugin
Some plugins exist precisely to give something to the rest of the application. For those, fastify-plugin removes the wall: whatever the plugin adds goes to its parent instead of staying inside.
npm install fastify-plugin Change src/plugins/openapi.ts to:
// src/plugins/openapi.ts import fp from 'fastify-plugin'; import swagger from '@fastify/swagger'; export default fp(async function openapiPlugin(fastify) { // The OpenAPI document is generated from the route schemas await fastify.register(swagger, { openapi: { openapi: '3.1.0', info: { title: 'My Fastify App', version: '1.0.0' }, }, }); fastify.get('/openapi.json', { schema: { hide: true } }, async () => fastify.swagger()); }, { name: 'openapi' }); Two lines changed: the function is wrapped in fp(...), and it gets a name. (The FastifyInstance annotation is gone because fp already knows the type of its argument.)
curl localhost:3000/openapi.json # ..."paths":{"/api/v1/users/":{...},"/api/v1/users/{id}":{...}} The routes are back.
When to use it
The rule that follows is simple:
- A plugin that provides something to others (a decorator, a hook, a database connection) is wrapped with
fastify-plugin. These live insrc/plugins/. - A plugin that contains routes is left as it is.
users.route.tsdoesn't usefp, and that's deliberate: whatever we add inside it later, a hook that requires a token for example, will apply to the users routes only.
The name is not decoration. It lets another plugin state what it needs:
export default fp(async function usersPlugin(fastify) { // ... }, { name: 'users', dependencies: ['database'] }); If no plugin named database has been registered before it, the application refuses to start:
The dependency 'database' of plugin 'users' is not registered An error at startup is far better than a fastify.pg is undefined on the first request.
await and registration order
app.register() is lazy: it only queues the plugin. Plugins are actually loaded when the app boots (ready() or listen()), one after the other, in registration order. That is why buildApp() can stay a normal synchronous function.
Inside a plugin, await fastify.register(...) waits until that child is fully loaded before the next line runs. You need it whenever the next line uses something the child added. Our plugin is an example: fastify.swagger() only exists once @fastify/swagger has been loaded, hence the await in front of its registration.
Scoping hooks to a group of routes
Encapsulation is what lets you apply a rule to some routes and not to others. Routes that need protection go in one plugin, the hook goes in the same plugin, and everything outside is untouched:
app.register(async function publicRoutes(fastify) { fastify.get('/public', async () => ({ public: true })); }); app.register(async function protectedRoutes(fastify) { fastify.addHook('onRequest', async (request, reply) => { if (!request.headers.authorization) { reply.code(401).send({ error: 'Unauthorized' }); return reply; // the response has been sent: stop here } }); fastify.get('/profile', async () => ({ profile: 'only with a token' })); }); GET /profile without an Authorization header answers 401; GET /public never sees the hook and answers 200. We'll build real authentication on this idea in chapter 12.
When an
asynchook sends the response itself,return replyafterwards. It tells Fastify that the request has been answered and nothing else should run. Fastify 5 notices a reply that was sent synchronously even if you forget, but when thesend()happens later (inside a callback, after anawaiton something else) thereturn replyis what keeps the handler from running too. Make it a habit.
⬅️ Previous chapter: Validation with schemas (TypeBox) · ➡️ Next chapter: Hooks and the request lifecycle
This article is part of the "Fastify with TypeScript" series — chapter 8 of 18.


