Lesson 15 / 30
Encapsulation & Scope
Keep plugins, routes, and hooks properly scoped to avoid conflicts.
Plugin scope isolation
Plugins registered inside another plugin are scoped to that plugin. Decorators, hooks, and routes don't leak to sibling plugins.
Nested plugins
Create sub-apps by registering a plugin that registers child plugins.
// routes/v1.js
export default async function v1Routes(fastify, opts) {
fastify.get('/health', async () => ({ version: '1' }));
}
// routes/v2.js
export default async function v2Routes(fastify, opts) {
fastify.get('/health', async () => ({ version: '2' }));
}
// server.js
fastify.register(v1Routes, { prefix: '/v1' });
fastify.register(v2Routes, { prefix: '/v2' });
// GET /v1/health -> { version: '1' }
// GET /v2/health -> { version: '2' }