UNPKG

7.47 kBMarkdownView Raw
1<h1 align="center">Fastify</h1>
2
3## Plugins
4Fastify allows the user to extend its functionalities with plugins.
5A plugin can be a set of routes, a server [decorator](https://github.com/fastify/fastify/blob/master/docs/Decorators.md) or whatever. The API that you will need to use one or more plugins, is `register`.<br>
6
7By default, `register` creates a *new scope*, this means that if you do some changes to the Fastify instance (via `decorate`), this change will not be reflected to the current context ancestors, but only to its sons. This feature allows us to achieve plugin *encapsulation* and *inheritance*, in this way we create a *direct acyclic graph* (DAG) and we will not have issues caused by cross dependencies.
8
9You already see in the [getting started](https://github.com/fastify/fastify/blob/master/docs/Getting-Started.md#register) section how using this API is pretty straightforward.
10```
11fastify.register(plugin, [options])
12```
13
14<a name="plugin-options"></a>
15### Plugin Options
16The optional `options` parameter for `fastify.register` supports a predefined set of options that Fastify itself will use, except when the plugin has been wrapped with [fastify-plugin](https://github.com/fastify/fastify-plugin). This options object will also be passed to the plugin upon invocation, regardless of whether or not the plugin has been wrapped. The currently supported list of Fastify specific options is:
17
18+ [`logLevel`](https://github.com/fastify/fastify/blob/master/docs/Routes.md#custom-log-level)
19+ [`prefix`](https://github.com/fastify/fastify/blob/master/docs/Plugins.md#route-prefixing-options)
20
21It is possible that Fastify will directly support other options in the future. Thus, to avoid collisions, a plugin should consider namespacing its options. For example, a plugin `foo` might be registered like so:
22
23```js
24fastify.register(require('fastify-foo'), {
25 prefix: '/foo',
26 foo: {
27 fooOption1: 'value',
28 fooOption2: 'value'
29 }
30})
31```
32
33If collisions are not a concern, the plugin may simply accept the options object as-is:
34
35```js
36fastify.register(require('fastify-foo'), {
37 prefix: '/foo',
38 fooOption1: 'value',
39 fooOption2: 'value'
40})
41```
42
43The `options` parameter can also be a `Function` which will be evaluated at the time the plugin is registered while giving access to the fastify instance via the first positional argument:
44
45```js
46const fp = require('fastify-plugin')
47
48fastify.register(fp((fastify, opts, next) => {
49 fastify.decorate('foo_bar', { hello: 'world' })
50
51 next()
52}))
53
54// The opts argument of fastify-foo will be { hello: 'world' }
55fastify.register(require('fastify-foo'), parent => parent.foo_bar)
56```
57
58The fastify instance passed on to the function is the latest state of the **external fastify instance** the plugin was declared on, allowing access to variables injected via [`decorate`](https://github.com/fastify/fastify/blob/master/docs/Decorators.md) by preceding plugins according to the **order of registration**. This is useful in case a plugin depends on changes made to the Fastify instance by a preceding plugin f.e. utilizing an existing database connection to wrap around it.
59
60Keep in mind that the fastify instance passed on to the function is the same as the one that will be passed in to the plugin, a copy of the external fastify instance rather than a reference. Any usage of the instance will behave the same as it would if called within the plugin's function i.e. if `decorate` is called, the decorated variables will be available within the plugin's function unless it was wrapped with [`fastify-plugin`](https://github.com/fastify/fastify-plugin).
61
62<a name="route-prefixing-option"></a>
63#### Route Prefixing option
64If you pass an option with the key `prefix` with a `string` value, Fastify will use it to prefix all the routes inside the register, for more info check [here](https://github.com/fastify/fastify/blob/master/docs/Routes.md#route-prefixing).<br>
65Be aware that if you use [`fastify-plugin`](https://github.com/fastify/fastify-plugin) this option won't work.
66
67<a name="error-handling"></a>
68#### Error handling
69The error handling is done by [avvio](https://github.com/mcollina/avvio#error-handling).<br>
70As general rule, it is highly recommended that you handle your errors in the next `after` or `ready` block, otherwise you will get them inside the `listen` callback.
71
72```js
73fastify.register(require('my-plugin'))
74
75// `after` will be executed once
76// the previous declared `register` has finished
77fastify.after(err => console.log(err))
78
79// `ready` will be executed once all the registers declared
80// have finished their execution
81fastify.ready(err => console.log(err))
82
83// `listen` is a special ready,
84// so it behaves in the same way
85fastify.listen(3000, (err, address) => {
86 if (err) console.log(err)
87})
88```
89
90*async-await* is supported only by `ready` and `listen`.
91```js
92fastify.register(require('my-plugin'))
93
94await fastify.ready()
95
96await fastify.listen(3000)
97```
98<a name="create-plugin"></a>
99### Create a plugin
100Creating a plugin is very easy, you just need to create a function that takes three parameters, the `fastify` instance, an options object and the next callback.<br>
101Example:
102```js
103module.exports = function (fastify, opts, next) {
104 fastify.decorate('utility', () => {})
105
106 fastify.get('/', handler)
107
108 next()
109}
110```
111You can also use `register` inside another `register`:
112```js
113module.exports = function (fastify, opts, next) {
114 fastify.decorate('utility', () => {})
115
116 fastify.get('/', handler)
117
118 fastify.register(require('./other-plugin'))
119
120 next()
121}
122```
123Sometimes, you will need to know when the server is about to close, for example because you must close a connection to a database. To know when this is going to happen, you can use the [`'onClose'`](https://github.com/fastify/fastify/blob/master/docs/Hooks.md#on-close) hook.
124
125Do not forget that `register` will always create a new Fastify scope, if you don't need that, read the following section.
126
127<a name="handle-scope"></a>
128### Handle the scope
129If you are using `register` only for extending the functionality of the server with [`decorate`](https://github.com/fastify/fastify/blob/master/docs/Decorators.md), it is your responsibility to tell Fastify to not create a new scope, otherwise your changes will not be accessible by the user in the upper scope.
130
131You have two ways to tell Fastify to avoid the creation of a new context:
132- Use the [`fastify-plugin`](https://github.com/fastify/fastify-plugin) module
133- Use the `'skip-override'` hidden property
134
135We recommend to using the `fastify-plugin` module, because it solves this problem for you, and you can pass a version range of Fastify as a parameter that your plugin will support.
136```js
137const fp = require('fastify-plugin')
138
139module.exports = fp(function (fastify, opts, next) {
140 fastify.decorate('utility', () => {})
141 next()
142}, '0.x')
143```
144Check the [`fastify-plugin`](https://github.com/fastify/fastify-plugin) documentation to know more about how use this module.
145
146If you don't use the `fastify-plugin` module, you can use the `'skip-override'` hidden property, but we do not recommend it. If in the future the Fastify API changes it will be a your responsibility update the module, while if you use `fastify-plugin`, you can be sure about backwards compatibility.
147```js
148function yourPlugin (fastify, opts, next) {
149 fastify.decorate('utility', () => {})
150 next()
151}
152yourPlugin[Symbol.for('skip-override')] = true
153module.exports = yourPlugin
154```