Fastify Plugin Encapsulation: Control Visibility Between Plugins
Fastify hides decorators and routes inside each register() call. Learn how to share them intentionally with fastify-plugin.
01 Jan 2026, 10:54 UTC

The problem: a decorator that works in one plugin but not another
You register two plugins under the same Fastify instance. Plugin A adds a decorator with fastify.decorate. Plugin B tries to read that decorator during route setup. At runtime the property is missing, and Fastify throws instead of failing when the file loads.
This is not a bug. It is encapsulation. Each register() call creates a new context in a tree. Decorators, hooks, and routes defined inside one branch are invisible to sibling branches unless you explicitly share them.
Useful takeaway: treat every plugin as a private scope. Share utilities only when you wrap the plugin with fastify-plugin or pass them through the parent instance.
How the encapsulation tree works
When you call app.register(plugin), Fastify creates a child context. Anything attached to that child—decorators, request hooks, error handlers, route prefixes—stays inside that boundary. A plugin registered later as a sibling cannot see what the first plugin attached to its own context.
Encapsulation applies to:
fastify.decorateanddecorateRequest/decorateReplyaddHookfor request lifecycle events- Route registration and prefix scopes
- Custom error handlers set with
setErrorHandler
Plugins load in the order you register them, but order does not break the boundary. A decorator defined in plugin A is still unavailable to plugin B just because B loads after A.
Worked example: isolated decorator
Create a file named app.js in your project root. This example registers two sibling plugins. Plugin A defines a decorator. Plugin B attempts to use it.
const Fastify = require('fastify')
const fp = require('fastify-plugin')
const app = Fastify({ logger: true })
// Plugin A: encapsulated by default
async function pluginA (fastify, options) {
fastify.decorate('utility', () => 'shared-value')
fastify.get('/a', async (request, reply) => {
return { source: 'plugin-a', utility: fastify.utility() }
})
}
// Plugin B: sibling, cannot see pluginA's decorator by default
async function pluginB (fastify, options) {
try {
// This runs at plugin registration time, not request time
console.log('utility from plugin B:', fastify.utility())
} catch (err) {
console.log('plugin B cannot access utility:', err.message)
}
fastify.get('/b', async (request, reply) => {
return { source: 'plugin-b' }
})
}
app.register(pluginA, { prefix: '/a' })
app.register(pluginB, { prefix: '/b' })
app.listen({ port: 3000 }, (err) => {
if (err) {
app.log.error(err)
process.exit(1)
}
})
Run this from your project directory:
node app.js
Where to run: terminal at the project root. Required permissions: none beyond normal file execution. Placeholders: none; the file is self-contained. Expected check: the console prints an error message from plugin B because fastify.utility is undefined inside plugin B's encapsulation boundary. Risk: none beyond a startup log message; the server still starts because the error is caught.
If you remove the try/catch, Fastify throws a runtime error when plugin B accesses fastify.utility. The failure happens when the plugin loads, not when you import the module.
Sharing state with fastify-plugin
To make plugin A's decorator visible to plugin B and the parent, wrap plugin A with fastify-plugin. This flattens the boundary upward to the immediate parent.
const Fastify = require('fastify')
const fp = require('fastify-plugin')
const app = Fastify({ logger: true })
async function pluginA (fastify, options) {
fastify.decorate('utility', () => 'shared-value')
fastify.get('/a', async (request, reply) => {
return { source: 'plugin-a', utility: fastify.utility() }
})
}
async function pluginB (fastify, options) {
// Now visible because pluginA was wrapped with fastify-plugin
console.log('utility from plugin B:', fastify.utility())
fastify.get('/b', async (request, reply) => {
return { source: 'plugin-b', utility: fastify.utility() }
})
}
app.register(fp(pluginA), { prefix: '/a' })
app.register(pluginB, { prefix: '/b' })
app.listen({ port: 3001 }, (err) => {
if (err) {
app.log.error(err)
process.exit(1)
}
})
Expected check: plugin B logs utility from plugin B: [Function: utility], and both routes respond successfully. The decorator is now available to the parent and all sibling plugins registered after it under the same parent.
Common mistakes and limits
- Calling
fastify-plugininside an already encapsulated plugin. It flattens visibility to the immediate parent only, not to every plugin in the tree. Do not nest it expecting global scope. - Accessing a decorator before its plugin registers. Fastify resolves decorators at runtime within the current context. Missing properties throw at runtime, not at import time.
- TypeScript module augmentation. You can declare decorator types so the editor is happy, but if the runtime plugin never loaded inside the current boundary, the property does not exist. Types do not create runtime state.
- Registering heavy plugins inside request hooks. Encapsulation separates namespaces; it does not isolate per-request CPU or memory. Loading a plugin inside a hook repeats that cost on every request.
Practical verification
- Create two sibling plugins under one parent Fastify instance.
- Add a decorator to only the first plugin.
- Attempt to read that decorator from the second plugin. Confirm it is undefined or throws.
- Wrap the first plugin with
fastify-pluginand repeat the check. Confirm the decorator is now visible to the sibling and parent.
Run the verification with Node.js LTS and a current Fastify release. If the behavior differs, check whether another plugin in your tree already wrapped the code with fastify-plugin, which can change the boundary unexpectedly.
Limitations
Encapsulation improves modularity and prevents name collisions, but it does not create security boundaries. Plugins share the same process and memory space. It also does not lazy-load code; every registered plugin contributes to startup time and memory use regardless of whether its routes are called.
If you need to share a utility without exposing it to every sibling, pass it through plugin options instead of using fastify-plugin. That keeps the dependency explicit and the boundary intact.