Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 39 ยท Plugins and Encapsulation

Encapsulation Explained

Understand Fastify encapsulation: how each plugin gets its own scope, what children inherit, why siblings cannot see each other and how to scope hooks safely.

Encapsulation is the idea that separates Fastify from most Node.js frameworks, and the one that confuses people the most. Each plugin gets its own context: a private copy of the instance. Hooks, decorators, schemas, error handlers and content-type parsers you add inside a plugin stay inside it (and its children). They do not leak out to the parent or to sibling plugins.

This is a feature, not a limitation. It lets you build a public API and an admin API in one server where only the admin routes require a login, and it prevents one team's plugin from accidentally changing the behavior of another's. This lesson explains the rules, demonstrates them, and shows how to deliberately break the wall when you need to (the next lesson covers that).

The inheritance rule

Think of a family tree. A child context inherits everything the parent had at the moment the child was created. Anything the child adds belongs to the child (and to its own descendants). Nothing flows upward or sideways.

flowchart TD
  ROOT["root: logger hook"] --> PUB["public plugin"]
  ROOT --> ADM["admin plugin: + auth hook"]
  ADM --> ADMU["admin/users plugin"]

The auth hook added in the admin plugin applies to the admin plugin and admin/users. The root and the public plugin never see it.

In summary:

Thing you add Visible to the plugin itself Visible to its children Visible to parent Visible to siblings
Hooks (addHook) yes yes no no
Decorators (decorate, decorateRequest, decorateReply) yes yes no no
Schemas (addSchema) yes yes no no
Error handler / not-found handler yes yes no no
Content-type parsers yes yes no no
Routes become part of the app

Routes are the exception in one sense: every route, wherever declared, is part of the one server and is reachable by URL. What encapsulation controls is which hooks, decorators and handlers apply to that route.

Decorators stay in their scope

Node.js A decorator is visible only where it was added

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The root's decorator (appName) is inherited by both plugins. currency exists only inside billing: the root does not have it, and the sibling reports cannot see it. In real Fastify, trying to use a missing decorator gives undefined (or a TypeError when you call it) and, for duplicates, decorate throws FST_ERR_DEC_ALREADY_PRESENT, which also stops two plugins from fighting over the same name in the same scope.

Hooks apply per scope

The most practical use of encapsulation is putting a hook where it belongs. A hook added on the root runs for every route. A hook added inside a plugin runs only for that plugin's routes. Here is a server with a public area and an area that needs an API key:

Node.js Protecting only one part of the app

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Compare the results. /public/time needs no key even though a hook was added elsewhere in the same file: the hook lives in privateApi's scope. /private/admin/reset, declared in a child of privateApi, inherits the key check automatically. This is how you write authentication once and cover a whole group of routes without per-route options.

Order matters: what the child inherits

A child copies the parent's hooks and decorators at the time the child loads, which happens when the parent finishes its own synchronous setup. Two practical rules follow:

  1. Hooks and decorators the parent adds before the child is loaded are inherited. In the usual style (register all plugins, then call ready) that includes anything the parent adds synchronously, even after the register(...) line in the same function, because the child has not loaded yet.
  2. Things the parent adds later, from asynchronous code or after an await, may be missed by a child that already loaded. Keep setup code synchronous where you can, and use await on register only deliberately.

When in doubt, register shared things (logging hooks, schemas, error handlers) first, then feature plugins.

Scoped error handlers and 404 pages

setErrorHandler and setNotFoundHandler are scoped like hooks. A common design is one JSON error format for /api and a friendlier HTML error page for the rest of the site. Register each handler inside the plugin it belongs to. A child without its own handler uses its parent's; with its own, it overrides it only for itself and its descendants.

Why Fastify works this way

  • Safety. A third-party plugin cannot change how your other routes behave. Everything it does is limited to its scope unless it is explicitly marked otherwise.
  • Clarity. To know what applies to a route, look at the plugin chain above it. There is no global mutable state hiding in the middle.
  • Testability. A plugin can be registered in a tiny test app with only what it needs.
  • Scale. Two large teams can add v1 and v2 APIs, each with its own hooks, schemas and error format, without coordinating.

You can inspect the plugin tree of a real app with app.printPlugins(), which draws the same family diagram as the mermaid figure above.

Common mistakes

  • "My hook doesn't run on the other routes." You added it inside a plugin; add it in an ancestor (or the root) for wider reach.
  • "My decorator is undefined in another plugin." It was added in a sibling scope. Either register the provider with fastify-plugin (next lesson) or move it to a common ancestor.
  • Decorating inside a route handler. Decoration must happen at start-up, never per request; Fastify checks the instance's shape for speed.
  • Wrapping everything in one big plugin just to be tidy. You lose the isolation benefits and get one giant scope.
  • Using the parent app variable inside a child plugin. Inside a plugin, use the instance parameter you were given; the outer app reaches the wrong scope and defeats encapsulation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A hook is added with addHook inside plugin A. Which routes does it affect?

    Hooks are scoped: they apply to the plugin that added them and its children, not to the parent or siblings.
  2. 2. Plugin A decorates the instance with 'cache'. Sibling plugin B tries to use this.cache. What happens?

    A sibling does not inherit anything from A. Use fastify-plugin or a common ancestor to share it.
  3. 3. Where would you add an authentication hook that must protect only /admin routes?

    A hook inside the admin plugin covers that plugin and its children, leaving public routes untouched.
  4. 4. What does a child plugin inherit from its parent?

    The child starts as a copy of the parent's context and then adds its own things privately.

Summary

  • Every register creates a child context; hooks, decorators, schemas, parsers and error handlers are scoped to it and its descendants.
  • Children inherit from the parent at load time; nothing flows to the parent or to siblings.
  • Put an auth hook inside the plugin of the protected routes and the rest of the app stays open.
  • Scoped error and 404 handlers let different areas return different formats.
  • To share something across scopes on purpose, use fastify-plugin (next lesson).

Next: Decorators in Depth