Code Reference

Fastify Plugins

Node.js · Reference cheat sheet

Fastify Plugins

Node.js · Reference cheat sheet


📋 Overview

Fastify organizes features as plugins. Each plugin gets an encapsulated context (decorators, hooks, routes) unless you break encapsulation deliberately.

🔧 Core concepts

APIRole
fastify.register(plugin, opts)Load plugin
fp (fastify-plugin)Share decorations with parent
decorate / decorateRequestAttach utilities
prefix optionMount routes under a path
PatternUse when
Encapsulated pluginIsolate routes/hooks per feature
fastify-plugin wrapperShare DB client, auth, config
Nested registerCreate contexts (e.g. /v1 vs /admin)

💡 Examples

Feature plugin:

async function usersPlugin(fastify, opts) {
  fastify.get("/", async () => []);
}
await fastify.register(usersPlugin, { prefix: "/users" });

Shared decoration with fp:

import fp from "fastify-plugin";

async function dbPlugin(fastify) {
  fastify.decorate("db", { query: async () => [] });
}
export default fp(dbPlugin);

Nested context:

await fastify.register(async (scope) => {
  scope.addHook("preHandler", async (req) => {
    /* admin-only */
  });
  scope.get("/stats", async () => ({ ok: true }));
}, { prefix: "/admin" });

⚠️ Pitfalls

  • Forgetting fastify-plugin means parent routes cannot see fastify.db.
  • Circular plugin dependencies are hard to debug — keep a clear register order.
  • Registering the same plugin twice can duplicate routes/hooks.

On this page