In Fastify everything is a plugin, your routes, your utilities and so on are all plugins. And to add a new plugin, whatever its functionality is, in Fastify

Registers

1
fastify.register(require('./my-plugin', opts, callback))

Register creates a new Fastify context, this means that if you do any change to the Fastify instance, that change will not be reflected into the context’s ancestors. In other words, encapsulated!

Required Plugins must expose a single function with the following signature:

1
module.exports = function (instance, opts, next) {}

The Fastify’s plugin module is fully reentrant and graph-based, it handles without any kind of problem asynchronous code and it guarantees the load order of the plugins, even the close order.

Decorators

Fastify offers you a way nice and elegant to wrote an utility: decorator.

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

Now you can access your utility by doing fastify.util.

1
2
3
4
fastify.register((instance, opts, next)=> {
instance.decorate('util', (a, b) => a + b)
next()
})

Hooks

Execute your utility.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fastify.register((instance, opts, next) => {
instance.decorate('util', (req, key, value) => { req.key = value })

instance.addHook('preHandler', (req, reply, done) => {
instance.util(req, 'timestamp', new Date())
done()
})

instance.get('/plugin1', (req, reply) => {
reply.send(req)
})

next()
})

fastify.get('/plugin2', (req, reply) => {
reply.send(req)
})