Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 39 ยท Plugins and Encapsulation

Plugins and register()

Everything in Fastify is a plugin. Learn how to write one, pass it options, give its routes a prefix, understand load order and split an app into modules.

Fastify's famous design principle is "everything is a plugin". Your routes, your database connection, your authentication, even the official CORS and rate-limiting packages are all plugins, and they all use the same mechanism: app.register(). Once this clicks, large Fastify applications become easy to organize, because a plugin is simply "a function that receives a Fastify instance and adds things to it".

This lesson is about writing and registering plugins. The next lesson explains the isolation rules that make them safe to combine.

What a plugin is

A plugin is a function with the signature (instance, options) => Promise | void:

JavaScript
async function userRoutes(app, options) {
  app.get('/', async () => [{ id: 1, name: 'Ada' }]);
  app.get('/:id', async (request) => ({ id: Number(request.params.id) }));
}

You use it by passing it to register:

JavaScript
app.register(userRoutes, { prefix: '/users' });

Three things to notice:

  1. The plugin's first parameter is a Fastify instance. It has get, post, addHook, decorate, register and everything else the root app has. It is not the same object as the parent though: it is a child instance (the next lesson explains why that matters).
  2. The second parameter is the options object you passed to register. The special key prefix is handled by Fastify itself: every route the plugin declares gets that prefix.
  3. Plugins can be async functions (preferred) or take a third done callback argument. Do not mix both; with an async function you simply return or throw.
Node.js A routes plugin with a prefix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

printRoutes() shows that the plugin's / and /:id became /users and /users/:id. The same plugin could be registered again with a different prefix (for example /v2/users), and its routes would exist twice without any copy-paste.

Passing options

The second argument to register is handed to the plugin untouched, so use it to configure behavior, never globals:

JavaScript
app.register(auditPlugin, { level: 'info', redact: ['password'] });

Inside the plugin you validate or default the options yourself. Keep defaults near the top, and read them from the argument, not from process.env; the application's start-up file is the one place that should read the environment, as the project structure lesson recommends.

register also accepts a function that returns the options. It receives the parent instance, which is useful when the options depend on something decorated earlier:

JavaScript
app.register(cachePlugin, (parent) => ({ ttl: parent.config.cacheTtl }));

When do plugins run?

register does not run the plugin immediately. It queues it. Plugins load when you call await app.ready() or app.listen(), in the order registered, and a plugin's own children load right after it, before the next sibling. A plugin must finish (its promise must resolve) before Fastify moves on, which is how a database plugin can open a connection before any routes that need it are registered.

flowchart TD
  R["root app"] --> A["plugin A (database)"]
  R --> B["plugin B (auth)"]
  R --> C["plugin C (routes)"]
  C --> C1["users routes"]
  C --> C2["orders routes"]

Loading order: A, then B, then C, then C's children C1 and C2. Each waits for the previous to finish.

Node.js Watching the load order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output carefully. All the register calls return before anything runs ("nothing has loaded"). Then database runs to completion, then routes; routes registers its children, finishes its own function, and only then are users and orders loaded. Understanding this order explains most "why is my decorator undefined?" problems: a plugin that needs something must be registered after the plugin that provides it.

Splitting an app into plugins

A typical layout groups routes by feature and wires them in one file:

TEXT
src/
  app.js               // builds the instance, registers plugins
  plugins/
    db.js              // opens the database, decorates app.db
    auth.js            // decorates app.authenticate
  routes/
    users.js           // export default async function (app) { ... }
    orders.js
JavaScript
// src/app.js
export async function buildApp(options = {}) {
  const app = Fastify(options);
  await app.register(import('./plugins/db.js'));
  await app.register(import('./plugins/auth.js'));
  await app.register(import('./routes/users.js'), { prefix: '/users' });
  await app.register(import('./routes/orders.js'), { prefix: '/orders' });
  return app;
}

Two helpful facts: you can pass import('./file.js') straight to register (Fastify unwraps the module's default export), and await app.register(...) is allowed, but not required: Fastify queues the calls anyway. Awaiting is only useful if the next lines of your own code depend on the plugin having loaded.

Exporting a builder function such as buildApp is what makes testing easy: each test creates a fresh app and calls app.inject(). The testing chapter shows this in detail.

Naming and options conventions

  • Name the plugin function (async function userRoutes) instead of exporting an anonymous arrow. Names appear in error messages and in app.printPlugins() output, which saves time when debugging.
  • Keep one concern per plugin. "Everything about orders" is a fine plugin; "misc setup" is not.
  • Do not mutate the options object. Copy it if you need to change values.
  • Throw early. If a required option is missing, throw inside the plugin; Fastify aborts start-up with a clear error instead of failing later at request time.

Common mistakes

  • Using async and done together. An async plugin that also takes done can call it twice or hang; choose one style.
  • Forgetting to await async work. If the plugin returns before the database connects, later plugins run too early.
  • Registering routes at the root and in plugins with the same URL, which throws a "duplicated route" error at start-up.
  • Expecting register to run immediately. Code right after app.register(...) does not see the plugin's decorators; use await app.ready() or the onReady hook.
  • Assuming a prefix is automatic for hooks. Hooks apply to routes in scope, not to URLs; the prefix only changes the URLs of routes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What are the parameters of a plugin function?

    A plugin receives a Fastify instance and the options passed to register. An async function needs no done callback.
  2. 2. When does the code inside a plugin run?

    register queues the plugin; plugins load in registration order when the app becomes ready.
  3. 3. What does the special option prefix do?

    prefix is handled by Fastify: a route '/' in a plugin registered with prefix '/users' answers at /users.
  4. 4. A routes plugin needs app.db, which another plugin decorates. What must you do?

    Plugins load in registration order, so the provider must be registered before the consumer.

Summary

  • A plugin is (instance, options) => Promise; app.register(plugin, options) adds it to the app.
  • The prefix option puts a path in front of all routes in the plugin, so one plugin can be mounted more than once.
  • Registration only queues a plugin; plugins load in order at ready(), children right after their parent.
  • Group code by feature, name your plugin functions and export a buildApp function for tests.
  • Register providers (database, auth) before the plugins that use them.

Next: Encapsulation Explained