Lesson 5 / 30

Plugins & Decorators

Extend Fastify with reusable plugins and decorators.

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.