SkillByAIOpen interactive version →

Lesson 5 / 32

Plugins & Decorators

Extend Fastify with reusable plugins and decorators that encapsulate databases, auth and shared helpers.

What are plugins?

Plugins are async functions that encapsulate functionality—database clients, authentication, middleware—and register routes, decorators, or hooks. They enable modular server design.

Writing a plugin

A plugin receives the Fastify instance and an options object. Register it with fastify.register(plugin, opts).

// plugins/database.js
export default async function dbPlugin(fastify, opts) {
  const db = { getUser: (id) => ({ id, name: 'Alice' }) };
  fastify.decorate('db', db);
}

// server.js
fastify.register(dbPlugin);
fastify.get('/users/:id', async (req, reply) => {
  const user = await fastify.db.getUser(req.params.id);
  return user;
});

Decorators add properties

fastify.decorate() adds a property to the Fastify instance, available in all routes. fastify.decorateRequest() adds to the request object, fastify.decorateReply() to the reply.

Await register ordering with ready()

Plugins load asynchronously in order. In tests call await app.ready() before using decorators, otherwise they may not exist yet.

Quick check

Quick check: What must a plugin function receive as its first argument?

  • The Node http server
  • A Fastify instance (encapsulated) and options
  • Only the options object
Answer

A Fastify instance (encapsulated) and options — The signature is `(instance, opts)` plus `done` unless it is async.