Plugins | Fastify (2024)

Plugins

Fastify allows the user to extend its functionalities with plugins. A plugin canbe a set of routes, a server decorator, or whatever. The APIthat you will need to use one or more plugins, is register.

By default, register creates a new scope, this means that if you make somechanges to the Fastify instance (via decorate), this change will not bereflected by the current context ancestors, but only by its descendants. Thisfeature allows us to achieve plugin encapsulation and inheritance, in thisway we create a directed acyclic graph (DAG) and we will not have issuescaused by cross dependencies.

You may have already seen in the GettingStarted guide how easy it isto use this API:

fastify.register(plugin, [options])

Plugin Options

The optional options parameter for fastify.register supports a predefinedset of options that Fastify itself will use, except when the plugin has beenwrapped with fastify-plugin. Thisoptions object will also be passed to the plugin upon invocation, regardless ofwhether or not the plugin has been wrapped. The currently supported list ofFastify specific options is:

Note: Those options will be ignored when used with fastify-plugin

It is possible that Fastify will directly support other options in the future.Thus, to avoid collisions, a plugin should consider namespacing its options. Forexample, a plugin foo might be registered like so:

fastify.register(require('fastify-foo'), {
prefix: '/foo',
foo: {
fooOption1: 'value',
fooOption2: 'value'
}
})

If collisions are not a concern, the plugin may simply accept the options objectas-is:

The options parameter can also be a Function that will be evaluated at thetime the plugin is registered while giving access to the Fastify instance viathe first positional argument:

const fp = require('fastify-plugin')

fastify.register(fp((fastify, opts, done) => {
fastify.decorate('foo_bar', { hello: 'world' })

done()
}))

// The opts argument of fastify-foo will be { hello: 'world' }
fastify.register(require('fastify-foo'), parent => parent.foo_bar)

The Fastify instance passed on to the function is the latest state of theexternal Fastify instance the plugin was declared on, allowing access tovariables injected via decorate by preceding pluginsaccording to the order of registration. This is useful in case a plugindepends on changes made to the Fastify instance by a preceding plugin i.e.utilizing an existing database connection to wrap around it.

Keep in mind that the Fastify instance passed on to the function is the same asthe one that will be passed into the plugin, a copy of the external Fastifyinstance rather than a reference. Any usage of the instance will behave the sameas it would if called within the plugins function i.e. if decorate is called,the decorated variables will be available within the plugins function unless itwas wrapped with fastify-plugin.

Route Prefixing option

If you pass an option with the key prefix with a string value, Fastify willuse it to prefix all the routes inside the register, for more info checkhere.

Be aware that if you wrap your routes withfastify-plugin, this option willnot work (there is a workaround available).

Error handling

The error handling is done byavvio.

As a general rule, it is highly recommended that you handle your errors in thenext after or ready block, otherwise you will get them inside the listencallback.

fastify.register(require('my-plugin'))

// `after` will be executed once
// the previous declared `register` has finished
fastify.after(err => console.log(err))

// `ready` will be executed once all the registers declared
// have finished their execution
fastify.ready(err => console.log(err))

// `listen` is a special ready,
// so it behaves in the same way
fastify.listen({ port: 3000 }, (err, address) => {
if (err) console.log(err)
})

async/await

async/await is supported by after, ready, and listen, as well asfastify being a Thenable.

await fastify.register(require('my-plugin'))

await fastify.after()

await fastify.ready()

await fastify.listen({ port: 3000 })

Note: Using await when registering a plugin loads the pluginand the underlying dependency tree, "finalizing" the encapsulation process.Any mutations to the plugin after it and its dependencies have beenloaded will not be reflected in the parent instance.

ESM support

ESM is supported as well from Node.jsv13.3.0 and above!

// main.mjs
import Fastify from 'fastify'
const fastify = Fastify()

fastify.register(import('./plugin.mjs'))

fastify.listen({ port: 3000 }, console.log)


// plugin.mjs
async function plugin (fastify, opts) {
fastify.get('/', async (req, reply) => {
return { hello: 'world' }
})
}

export default plugin

Create a plugin

Creating a plugin is very easy, you just need to create a function that takesthree parameters, the fastify instance, an options object, and the donecallback.

Example:

module.exports = function (fastify, opts, done) {
fastify.decorate('utility', function () {})

fastify.get('/', handler)

done()
}

You can also use register inside another register:

module.exports = function (fastify, opts, done) {
fastify.decorate('utility', function () {})

fastify.get('/', handler)

fastify.register(require('./other-plugin'))

done()
}

Sometimes, 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 tohappen, you can use the 'onClose' hook.

Do not forget that register will always create a new Fastify scope, if you donot need that, read the following section.

Handle the scope

If you are using register only for extending the functionality of the serverwith decorate, it is your responsibility to tell Fastifynot to create a new scope. Otherwise, your changes will not be accessible by theuser in the upper scope.

You have two ways to tell Fastify to avoid the creation of a new context:

We recommend using the fastify-plugin module, because it solves this problemfor you, and you can pass a version range of Fastify as a parameter that yourplugin will support.

const fp = require('fastify-plugin')

module.exports = fp(function (fastify, opts, done) {
fastify.decorate('utility', function () {})
done()
}, '0.x')

Check the fastify-plugindocumentation to learn more about how to use this module.

If you do not 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 APIchanges it will be your responsibility to update the module, while if you usefastify-plugin, you can be sure about backward compatibility.

function yourPlugin (fastify, opts, done) {
fastify.decorate('utility', function () {})
done()
}
yourPlugin[Symbol.for('skip-override')] = true
module.exports = yourPlugin
Plugins | Fastify (2024)
Top Articles
Obligation definition — AccountingTools
What is ISO 20022 and How Will it Impact the Crypto Industry?
Craigslist Livingston Montana
My Arkansas Copa
Login Page
Botw Royal Guard
Uihc Family Medicine
Missing 2023 Showtimes Near Cinemark West Springfield 15 And Xd
Chelsea player who left on a free is now worth more than Palmer & Caicedo
What is international trade and explain its types?
Our History | Lilly Grove Missionary Baptist Church - Houston, TX
A Fashion Lover's Guide To Copenhagen
Catsweb Tx State
FIX: Spacebar, Enter, or Backspace Not Working
Superhot Unblocked Games
Rosemary Beach, Panama City Beach, FL Real Estate & Homes for Sale | realtor.com®
Classic Lotto Payout Calculator
Craigslist List Albuquerque: Your Ultimate Guide to Buying, Selling, and Finding Everything - First Republic Craigslist
Fool’s Paradise movie review (2023) | Roger Ebert
Gdlauncher Downloading Game Files Loop
2016 Hyundai Sonata Refrigerant Capacity
Craigslist Toy Hauler For Sale By Owner
Craigslist In Visalia California
Effingham Bookings Florence Sc
Doublelist Paducah Ky
How to Grow and Care for Four O'Clock Plants
[PDF] NAVY RESERVE PERSONNEL MANUAL - Free Download PDF
Shreveport City Warrants Lookup
Reser Funeral Home Obituaries
Accuweather Minneapolis Radar
Pixel Combat Unblocked
Town South Swim Club
Evil Dead Rise Showtimes Near Regal Sawgrass & Imax
Murphy Funeral Home & Florist Inc. Obituaries
Microsoftlicentiespecialist.nl - Microcenter - ICT voor het MKB
Breckie Hill Fapello
Back to the Future Part III | Rotten Tomatoes
Final Exam Schedule Liberty University
Dr Adj Redist Cadv Prin Amex Charge
Trap Candy Strain Leafly
Jasgotgass2
Dispensaries Open On Christmas 2022
Craigslist Com Panama City Fl
Immobiliare di Felice| Appartamento | Appartamento in vendita Porto San
Hkx File Compatibility Check Skyrim/Sse
Royals Yankees Score
National Weather Service Richmond Va
Darkglass Electronics The Exponent 500 Test
Syrie Funeral Home Obituary
Oak Hill, Blue Owl Lead Record Finastra Private Credit Loan
The Missile Is Eepy Origin
Lorcin 380 10 Round Clip
Latest Posts
Article information

Author: Lidia Grady

Last Updated:

Views: 5946

Rating: 4.4 / 5 (45 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Lidia Grady

Birthday: 1992-01-22

Address: Suite 493 356 Dale Fall, New Wanda, RI 52485

Phone: +29914464387516

Job: Customer Engineer

Hobby: Cryptography, Writing, Dowsing, Stand-up comedy, Calligraphy, Web surfing, Ghost hunting

Introduction: My name is Lidia Grady, I am a thankful, fine, glamorous, lucky, lively, pleasant, shiny person who loves writing and wants to share my knowledge and understanding with you.