← Back to Node.js, page 4

nodejs-0069 · Hard senior

How do Fastify plugins and encapsulation work, and when do you use fastify-plugin?

Every plugin registered with app.register runs in its own encapsulated context. Decorators, hooks and routes added inside it are visible to that plugin and its children, but not to parents or siblings. Wrapping a plugin with fastify-plugin removes that boundary, so shared things such as a database client become available to the whole app.

Full answer

In Fastify, an application is a tree of plugins. app.register(plugin, options) creates a child context. Each context inherits from its parent:

  • Decorators (app.decorate('db', ...), request.decorate, reply.decorate) added in a child are not visible outside it.
  • Hooks added in a child apply only to routes inside that context and its children.
  • Routes registered in a context get the prefix option of that register call (for example /api/v1).

Why this design? It keeps modules isolated. A plugin for admin routes can add an authentication hook that does not touch public routes. Two plugins cannot clash over a decorator name. It also makes the load order explicit: Fastify loads plugins with avvio, and await app.ready() waits for all of them.

When you want to share something with the parent (a database connection, a configuration object, a metrics hook for every route), the plugin must break encapsulation. fastify-plugin does that: fp(async function (app) { ... }) sets the skip-override marker, so the plugin runs in the parent's context. It can also declare a name, dependencies and a version range for Fastify.

Guidelines:

  • Wrap shared infrastructure plugins in fp. Keep route plugins unwrapped.
  • Use options to pass configuration. Do not read globals inside plugins.
  • Close resources with the onClose hook, so app.close() shuts everything down.
  • Split by feature (students, courses), not by technical layer.

A common mistake is registering a database plugin without fp and then finding that app.db is undefined in sibling plugins.

javascript
const Fastify = require('fastify');
const fp = require('fastify-plugin');

async function main() {
  const app = Fastify();

  // Plugin 1: encapsulated. Its decorator stays inside.
  app.register(async function privatePlugin(instance) {
    instance.decorate('secret', 'only visible inside');
    instance.addHook('onRequest', async (request, reply) => { reply.header('x-from-private-plugin', 'yes'); });
    instance.get('/inside', async () => ({ secret: instance.secret }));
  });

  // Plugin 2: wrapped with fastify-plugin, so the decorator is shared with the parent.
  app.register(fp(async function sharedPlugin(instance) {
    instance.decorate('db', { find: (id) => ({ id, name: 'Asha' }) });
  }, { name: 'shared-db' }));

  // A route in the root context.
  app.get('/outside', async () => ({
    seesSecret: typeof app.secret,
    seesDb: typeof app.db,
    student: app.db.find(1),
  }));

  // A prefixed route group that uses the shared decorator.
  app.register(async function api(instance) {
    instance.get('/student/:id', async (request) => instance.db.find(Number(request.params.id)));
  }, { prefix: '/api/v1' });

  await app.ready();

  for (const url of ['/inside', '/outside', '/api/v1/student/7']) {
    const res = await app.inject(url);
    console.log(url.padEnd(18), res.statusCode, res.body, '| private hook header:', res.headers['x-from-private-plugin'] || 'none');
  }
  await app.close();
}

main();

The private hook only adds its header to routes inside its own plugin. Install first with npm install fastify fastify-plugin (run here with fastify 5.12.8, fastify-plugin 6.0.1). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): /inside 200 {"secret":"only visible inside"} | private hook header: yes /outside 200 {"seesSecret":"undefined","seesDb":"object","student":{"id":1,"name":"Asha"}} | private hook header: none /api/v1/student/7 200 {"id":7,"name":"Asha"} | private hook header: none

Key points

  • register creates an encapsulated child context.
  • Decorators and hooks stay inside their context.
  • fastify-plugin shares a plugin with the parent context.
  • Use onClose to release resources.

Common mistakes

  • Registering a database plugin without fastify-plugin and then not finding the decorator.
  • Wrapping every plugin in fp and losing the isolation.
  • Using a hook on the root app when it should apply to one group of routes.
  • Forgetting await app.ready() before using decorated values.

Follow-ups

  • How does Fastify decide the load order of plugins?
  • How do you test one plugin in isolation?
  • When would you choose encapsulation over a shared hook?

Tips

  • Describe the tree of contexts in one sentence.
  • Say when you reach for fp: shared infrastructure.
  • Mention onClose for clean shutdown.