Fastify: when to use a plugin instead of a regular module?

Viewed 86

I’m a little confused about when to use plugins in Fastify.js. For example, if I just have a lib/utils.js file with some utility functions, I would normally just require() them throughout my app wherever needed. Is there some great benefit to making my utils plugins instead? When would I do a plugin instead of a plain js require()?

1 Answers

My understanding is that plugins are useful for ecapsulation. As mentioned in the plugin docs. Anytime register is called a new scope is created which means that things added to fastify via decorate calls stays within that scope. The goal of this is to make sure fastify plugins do not have any issues due to cross dependencies. So when you need a new scope, use plugins. Otherwise you can use whatever you please.

Related