fastify-plugin

Wraps a plugin so its decorators and hooks apply to the parent scope (breaking encapsulation).

Since Fastify 5 Spec ↗

Syntax

fp(async (instance, opts) => {}, options?)

Parameters

NameTypeRequiredDescription
fn FastifyPluginAsync No The plugin function to wrap.
options object No Metadata like name, fastify (version range), and dependencies.

Returns

FastifyPluginCallback — A plugin that does not create a new context.

Examples

import fp from 'fastify-plugin';
import type { FastifyPluginAsync } from 'fastify';

const dbPlugin: FastifyPluginAsync = async (app) => {
  const db = await connect();
  app.decorate('db', db);
  app.addHook('onClose', async () => db.end());
};

export default fp(dbPlugin, { name: 'db' });

Notes

Use fastify-plugin for shared infrastructure (db, auth, config) that must be visible to sibling plugins and the root. Without it, decorators stay trapped in the plugin's own encapsulated scope.