Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 39 ยท Plugins and Encapsulation

fastify-plugin and Sharing Across Scopes

Learn when and how to use fastify-plugin to break encapsulation on purpose: sharing a database, config or auth across plugins, plugin metadata and common pitfalls.

Encapsulation keeps plugins from affecting each other, but sometimes you want a plugin to affect everyone. A database plugin should give app.db to all your route plugins. An authentication plugin should add app.authenticate to the whole app. A configuration plugin should add app.config everywhere.

If you register such a plugin the normal way, its decorators are trapped in its own child scope and your other plugins see undefined. The fix is a tiny wrapper called fastify-plugin (usually imported as fp). It marks a plugin as "do not create a new scope": the plugin's decorators, hooks and schemas are applied directly to the parent instead.

The problem, demonstrated

The first example registers a db plugin the plain way. The second wraps it with fp. Everything else is identical.

Node.js Without fp the decorator is trapped; with fp it is shared

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.

With the plain plugin, routes is a sibling and cannot see db. Wrapped with fp, the decorator is added to the parent's scope, so every plugin registered afterwards (and the parent itself) can use it.

Using fastify-plugin

In a real project you install the package (npm install fastify-plugin) and wrap the exported function:

JavaScript
// plugins/db.js
import fp from 'fastify-plugin';
import { createPool } from './pool.js';

export default fp(async function db(app, options) {
  const pool = createPool(options.connectionString);
  app.decorate('db', pool);
  app.addHook('onClose', async () => pool.end());
}, {
  name: 'db',
});

Here is what fp does under the hood: it sets a hidden flag (the one the stand-in's fp sets) that tells Fastify "run this plugin with the parent's instance, not a child". That is the only magic. Because fastify-plugin is not installed on this site, the runnable examples define the same few-line fp function inside the stand-in.

Metadata: name, dependencies, fastify

The second argument to fp is optional metadata that makes problems appear at start-up instead of in production:

JavaScript
export default fp(authPlugin, {
  name: 'auth',
  dependencies: ['db'],       // load error if no plugin named 'db' was registered before
  fastify: '5.x',             // load error on a different Fastify major version
  decorators: { fastify: ['db'] },   // load error unless app.db exists
});
  • name identifies the plugin in error messages and is what other plugins list in dependencies.
  • dependencies declares which named plugins must already be registered.
  • decorators lists decorators that must exist (fastify, request and reply keys).
  • fastify is a semver range of supported Fastify versions. If you publish a plugin for others, set it.

If a dependency is missing, Fastify throws while loading plugins with a message that names the missing piece, which is far friendlier than "Cannot read properties of undefined (reading 'query')" on the first request.

Hooks inside an fp plugin go global

An fp plugin shares everything with the parent: not just decorators, but hooks, schemas, parsers and error handlers too. That is a common source of surprises:

Node.js A hook inside an fp plugin affects the whole parent scope

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.

/scoped has only its own hook. /later and /nested get [stamped] because the fp plugin put its hook on the root scope, which both inherit. Notice that /scoped is registered before the fp plugin loads, so it does not get [stamped] (it copied the root's hooks earlier). That order-dependence is why hooks that must apply everywhere should be registered first.

When to use fp, and when not to

Use fp for Do not use fp for
Database / cache / queue clients (app.db) Route plugins (let them be encapsulated)
Configuration and environment (app.config) Hooks that should protect only one area
Authentication helpers (app.authenticate) Admin-only or version-specific functionality
Shared schemas and error handler Anything meant to be mounted twice with different options
Cross-cutting utilities (CORS, helmet, sensible) Plugins with state that must stay private

A good rule: infrastructure plugins use fp; feature plugins do not. Official plugins such as @fastify/cors, @fastify/helmet and @fastify/jwt are wrapped with fp already, so registering them affects the scope you register them in.

Registering an fp plugin in the right place

Because fp applies to the current scope, where you register matters:

  • Registered on the root, it covers the whole app.
  • Registered inside a feature plugin, it covers just that feature (and its children). For example, instance.register(fp(auditPlugin)) inside the admin plugin affects only admin routes.

So fp does not mean "global". It means "use the scope I was registered in, rather than a new one". That makes it equally useful for local sharing between a plugin and its children.

Common mistakes

  • Not wrapping a plugin that decorates the instance and then getting undefined in a sibling plugin.
  • Wrapping route plugins with fp, which removes their isolation and lets their hooks leak onto unrelated routes. Wrap only infrastructure.
  • Registering the consumer before the provider. fp shares the decorator once loaded; the consumer must load afterwards (or declare dependencies).
  • Registering the same fp plugin twice in one scope. A second decorate('db', ...) throws FST_ERR_DEC_ALREADY_PRESENT; register it once, at the highest scope that needs it.
  • Forgetting onClose. A plugin that opens a connection must close it in an onClose hook, or tests and shutdowns hang.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does wrapping a plugin with fastify-plugin change?

    fp marks the plugin as not encapsulated, so its decorators, hooks and schemas apply directly to the parent instance.
  2. 2. Which plugin is the best candidate for fp?

    Infrastructure that every other plugin needs should be shared; feature plugins should stay encapsulated.
  3. 3. What does the dependencies option in fp metadata do?

    dependencies lists plugin names that must already be registered, so mistakes appear at start-up.
  4. 4. You register an fp plugin that adds an onSend hook on the root. Which routes get the hook?

    The hook lands on the parent scope. Plugins that already copied the parent's hooks earlier do not get it.

Summary

  • Plugins are encapsulated by default; fp(plugin) makes a plugin share its decorators, hooks and schemas with the scope it is registered in.
  • Use it for infrastructure (database, config, auth, CORS) and not for feature or route plugins.
  • Metadata (name, dependencies, decorators, fastify) turns missing pieces into clear start-up errors.
  • Hooks in an fp plugin apply to the parent scope and to plugins that load afterwards.
  • fp means "use the scope I was registered in", so it works at any level of the tree.

Next: Official Plugins and Autoload