The hitchhiker’s guide to plugins

    Fastify was built from the beginning to be an extremely modular system. We built a powerful API that allows you to add methods and utilities to Fastify by creating a namespace. We built a system that creates an encapsulation model, which allows you to split your application into multiple microservices at any moment, without the need to refactor the entire application.

    Table of contents

    As with JavaScript, where everything is an object, in Fastify everything is a plugin.
    Your routes, your utilities, and so on are all plugins. To add a new plugin, whatever its functionality may be, in Fastify you have a nice and unique API: .

    register creates a new Fastify context, which means that if you perform any changes on the Fastify instance, those changes will not be reflected in the context’s ancestors. In other words, encapsulation!

    Why is encapsulation important?
    Well, let’s say you are creating a new disruptive startup, what do you do? You create an API server with all your stuff, everything in the same place, a monolith!
    Ok, you are growing very fast and you want to change your architecture and try microservices. Usually, this implies a huge amount of work, because of cross dependencies and a lack of separation of concerns in the codebase.
    Fastify helps you in that regard. Thanks to the encapsulation model, it will completely avoid cross dependencies and will help you structure your code into cohesive blocks.

    Let’s return to how to correctly use register.
    As you probably know, the required plugins must expose a single function with the following signature

    1. module.exports = function (fastify, options, done) {}

    Where fastify is the encapsulated Fastify instance, options is the options object, and done is the function you must call when your plugin is ready.

    Fastify’s plugin model is fully reentrant and graph-based, it handles asynchronous code without any problems and it enforces both the load and close order of plugins. How? Glad you asked, check out avvio! Fastify starts loading the plugin after .listen(), .inject() or .ready() are called.

    Inside a plugin you can do whatever you want, register routes, utilities (we will see this in a moment) and do nested registers, just remember to call done when everything is set up!

    1. module.exports = function (fastify, options, done) {
    2. fastify.get('/plugin', (request, reply) => {
    3. reply.send({ hello: 'world' })
    4. })
    5. done()
    6. }

    Well, now you know how to use the register API and how it works, but how do we add new functionality to Fastify and even better, share them with other developers?

    Decorators

    Okay, let’s say that you wrote a utility that is so good that you decided to make it available along with all your code. How would you do it? Probably something like the following:

    1. // your-awesome-utility.js
    2. module.exports = function (a, b) {
    3. return a + b
    4. }
    1. const util = require('./your-awesome-utility')
    2. console.log(util('that is ', 'awesome'))

    Now you will import your utility in every file you need it in. (And do not forget that you will probably also need it in your tests).

    Fastify offers you a more elegant and comfortable way to do this, decorators. Creating a decorator is extremely easy, just use the decorate API:

    1. fastify.decorate('util', (a, b) => a + b)

    Now you can access your utility just by calling fastify.util whenever you need it - even inside your test.
    And here starts the magic; do you remember how just now we were talking about encapsulation? Well, using register and decorate in conjunction enable exactly that, let me show you an example to clarify this:

    1. fastify.register((instance, opts, done) => {
    2. instance.decorate('util', (a, b) => a + b)
    3. console.log(instance.util('that is ', 'awesome'))
    4. done()
    5. })
    6. fastify.register((instance, opts, done) => {
    7. console.log(instance.util('that is ', 'awesome')) // This will throw an error
    8. done()
    9. })

    Do note that encapsulation applies to the ancestors and siblings, but not the children.

    Take home message: if you need a utility that is available in every part of your application, take care that it is declared in the root scope of your application. If that is not an option, you can use the fastify-plugin utility as described .

    decorate is not the only API that you can use to extend the server functionality, you can also use decorateRequest and decorateReply.

    decorateRequest and decorateReply? Why do we need them if we already have decorate?
    Good question, we added them to make Fastify more developer-friendly. Let’s see an example:

    1. fastify.decorate('html', payload => {
    2. return generateHtml(payload)
    3. })
    4. fastify.get('/html', (request, reply) => {
    5. reply
    6. .type('text/html')
    7. .send(fastify.html({ hello: 'world' }))
    8. })

    It works, but it could be much better!

    1. fastify.decorateReply('html', function (payload) {
    2. this.type('text/html') // This is the 'Reply' object
    3. this.send(generateHtml(payload))
    4. })
    5. fastify.get('/html', (request, reply) => {
    6. reply.html({ hello: 'world' })
    7. })

    In the same way you can do this for the request object:

    1. fastify.decorate('getHeader', (req, header) => {
    2. return req.headers[header]
    3. })
    4. fastify.addHook('preHandler', (request, reply, done) => {
    5. request.isHappy = fastify.getHeader(request.raw, 'happy')
    6. done()
    7. })
    8. fastify.get('/happiness', (request, reply) => {
    9. reply.send({ happy: request.isHappy })
    10. })

    Again, it works, but it can be much better!

    1. fastify.decorateRequest('setHeader', function (header) {
    2. this.isHappy = this.headers[header]
    3. })
    4. fastify.decorateRequest('isHappy', false) // This will be added to the Request object prototype, yay speed!
    5. fastify.addHook('preHandler', (request, reply, done) => {
    6. request.setHeader('happy')
    7. done()
    8. })
    9. fastify.get('/happiness', (request, reply) => {
    10. reply.send({ happy: request.isHappy })
    11. })

    We have seen how to extend server functionality and how to handle the encapsulation system, but what if you need to add a function that must be executed every time when the server “emits“ an event?

    Hooks

    You just built an amazing utility, but now you need to execute that for every request, this is what you will likely do:

    1. fastify.decorate('util', (request, key, value) => { request[key] = value })
    2. fastify.get('/plugin1', (request, reply) => {
    3. fastify.util(request, 'timestamp', new Date())
    4. reply.send(request)
    5. })
    6. fastify.get('/plugin2', (request, reply) => {
    7. fastify.util(request, 'timestamp', new Date())
    8. reply.send(request)
    9. })

    I think we all agree that this is terrible. Repeated code, awful readability and it cannot scale.

    So what can you do to avoid this annoying issue? Yes, you are right, use a hook!

    1. fastify.decorate('util', (request, key, value) => { request[key] = value })
    2. fastify.addHook('preHandler', (request, reply, done) => {
    3. fastify.util(request, 'timestamp', new Date())
    4. done()
    5. })
    6. fastify.get('/plugin1', (request, reply) => {
    7. reply.send(request)
    8. })
    9. fastify.get('/plugin2', (request, reply) => {
    10. reply.send(request)
    11. })

    Now for every request, you will run your utility. You can register as many hooks as you need.
    Sometimes you want a hook that should be executed for just a subset of routes, how can you do that? Yep, encapsulation!

    Now your hook will run just for the first route!

    As you probably noticed by now, request and reply are not the standard Nodejs request and response objects, but Fastify’s objects.

    The preferred way to distribute a utility is to wrap all your code inside a register. Using this, your plugin can support asynchronous bootstrapping (since decorate is a synchronous API), in the case of a database connection for example.

    Wait, what? Didn’t you tell me that register creates an encapsulation and that the stuff I create inside will not be available outside?
    Yes, I said that. However, what I didn’t tell you is that you can tell Fastify to avoid this behavior with the module.

    1. const fp = require('fastify-plugin')
    2. const dbClient = require('db-client')
    3. fastify.decorate('db', conn)
    4. done()
    5. })
    6. }
    7. module.exports = fp(dbPlugin)

    You can also tell fastify-plugin to check the installed version of Fastify, in case you need a specific API.

    As we mentioned earlier, Fastify starts loading its plugins after .listen(), .inject() or .ready() are called and as such, after they have been declared. This means that, even though the plugin may inject variables to the external Fastify instance via decorate, the decorated variables will not be accessible before calling .listen(), .inject() or .ready().

    In case you rely on a variable injected by a preceding plugin and want to pass that in the options argument of register, you can do so by using a function instead of an object:

    1. const fastify = require('fastify')()
    2. const fp = require('fastify-plugin')
    3. const dbClient = require('db-client')
    4. function dbPlugin (fastify, opts, done) {
    5. dbClient.connect(opts.url, (err, conn) => {
    6. fastify.decorate('db', conn)
    7. done()
    8. })
    9. }
    10. fastify.register(fp(dbPlugin), { url: 'https://example.com' })
    11. fastify.register(require('your-plugin'), parent => {
    12. return { connection: parent.db, otherOption: 'foo-bar' }
    13. })

    In the above example, the parent variable of the function passed in as the second argument of register is a copy of the external Fastify instance that the plugin was registered at. This means that we are able to access any variables that were injected by preceding plugins in the order of declaration.

    ESM support

    ESM is supported as well from Node.js v13.3.0 and above! Just export your plugin as ESM module and you are good to go!

    1. // plugin.mjs
    2. async function plugin (fastify, opts) {
    3. fastify.get('/', async (req, reply) => {
    4. return { hello: 'world' }
    5. })
    6. }
    7. export default plugin

    Note: Fastify does not support named imports within an ESM context. Instead, the default export is available.

    1. // server.mjs
    2. import Fastify from 'fastify'
    3. const fastify = Fastify()
    4. ///...
    5. fastify.listen(3000, (err, address) => {
    6. if (err) {
    7. fastify.log.error(err)
    8. process.exit(1)
    9. }
    10. })

    Handle errors

    It can happen that one of your plugins fails during startup. Maybe you expect it and you have a custom logic that will be triggered in that case. How can you implement this? The after API is what you need. after simply registers a callback that will be executed just after a register, and it can take up to three parameters.
    The callback changes based on the parameters you are giving:

    1. If no parameter is given to the callback and there is an error, that error will be passed to the next error handler.
    2. If one parameter is given to the callback, that parameter will be the error object.
    3. If two parameters are given to the callback, the first will be the error object; the second will be the done callback.
    4. If three parameters are given to the callback, the first will be the error object, the second will be the top-level context unless you have specified both server and override, in that case, the context will be what the override returns, and the third the done callback.

    Let’s see how to use it:

    1. fastify
    2. .register(require('./database-connector'))
    3. .after(err => {
    4. if (err) throw err
    5. })

    If your plugin needs to expose custom errors, you can easily generate consistent error objects across your codebase and plugins with the fastify-error module.

    1. const createError = require('fastify-error')
    2. console.log(new CustomError())

    Emit Warnings

    If you want to deprecate an API, or you want to warn the user about a specific use case, you can use the fastify-warning module.

    Let’s start!

    Awesome, now you know everything you need to know about Fastify and its plugin system to start building your first plugin, and please if you do, tell us! We will add it to the ecosystem section of our documentation!

    If you want to see some real-world examples, check out:

    • Templates rendering (ejs, pug, handlebars, marko) plugin support for Fastify.
    • fastify-mongodb Fastify MongoDB connection plugin, with this you can share the same MongoDB connection pool in every part of your server.
    • Multipart support for Fastify
    • fastify-helmet Important security headers for Fastify