Fastify plugins and encapsulation
Framework lane: Fastify 5.x, documentation lane 5.6.x. Exact supported patch, dependency lock, advisory review and execution are NOT RUN. The framework code is a static candidate; do not install dependencies or expose a server automatically. The local companion uses Node.js 22.16.0 and requires no third-party packages.
Framework example — staged
import Fastify from 'fastify';const app = Fastify();app.register(async child => { child.decorate('catalogLabel', 'books'); child.get('/label', async () => ({label:child.catalogLabel}));}, {prefix:'/catalog'});try { const response = await app.inject('/catalog/label'); console.log(response.statusCode, response.body, app.hasDecorator('catalogLabel'));} finally { await app.close(); }Expected behavior (not observed): Expected 200, {"label":"books"} and false for the parent decoration check.
How it works
Register a plugin with register and optionally a route prefix. A decoration adds a named capability to the instance or request as appropriate. Normal plugin scopes inherit from ancestors; special plugins can deliberately change encapsulation, so inspect plugin packaging. Prefer explicit scope and avoid accidental global state. The plugin below is an ordinary async function, not wrapped by fastify-plugin.
Practice the underlying idea without dependencies
const parent = { region: 'demo' };const child = Object.create(parent);child.label = 'books';const sibling = Object.create(parent);console.log(child.region, child.label, String(sibling.label));Run node main.mjs in a disposable directory. Expected output:
demo books undefinedThis tests the illustrated JavaScript behavior only, not the framework.
Common mistake
The JavaScript prototype example illustrates visibility only; it is not Fastify’s implementation. Do not assume registering a plugin gives unrelated sibling plugins access to its decorations.
Apply it yourself
Plan two sibling plugins, catalog and shipping, and identify which dependency belongs at the parent scope.
Further reading
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Fastify plugins and encapsulation — knowledge check
Apply the lesson’s contracts and identify common boundary mistakes.
What path does /label use with prefix /catalog?
Can ordinary child decorations automatically be read by siblings?
What does the prototype example establish?