Book Image

Accelerating Server-Side Development with Fastify

By : Manuel Spigolon, Maksim Sinik, Matteo Collina
5 (1)
Book Image

Accelerating Server-Side Development with Fastify

5 (1)
By: Manuel Spigolon, Maksim Sinik, Matteo Collina

Overview of this book

This book is a complete guide to server-side app development in Fastify, written by the core contributors of this highly performant plugin-based web framework. Throughout the book, you’ll discover how it fosters code reuse, thereby improving your time to market. Starting with an introduction to Fastify’s fundamental concepts, this guide will lead you through the development of a real-world project while providing in-depth explanations of advanced topics to prepare you to build highly maintainable and scalable backend applications. The book offers comprehensive guidance on how to design, develop, and deploy RESTful applications, including detailed instructions for building reusable components that can be leveraged across multiple projects. The book presents guidelines for creating efficient, reliable, and easy-to-maintain real-world applications. It also offers practical advice on best practices, design patterns, and how to avoid common pitfalls encountered by developers while building backend applications. By following these guidelines and recommendations, you’ll be able to confidently design, implement, deploy, and maintain an application written in Fastify, and develop plugins and APIs to contribute to the Fastify and open source communities.
Table of Contents (21 chapters)
Part 1:Fastify Basics
Part 2:Build a Real-World Project
Part 3:Advanced Topics

Adding a basic plugin instance

Previously, we talked about a plugin instance as a child component of an application instance.

To create one, you simply need to write the following:

app.register(function myPlugin(pluginInstance, opts, next) {'I am a plugin instance,
    children of app')
}, { hello: 'the opts object' })

These simple lines have just created an encapsulated context: this means that every event, hook, plugin, and decorator registered in the myPlugin function scope will remain inside that context and all its children. Optionally, you can provide an input object as a second parameter to the register function. This will propagate the input to the plugin’s opts parameter. If you move the plugin to another file, this will become extremely useful when sharing a configuration through files.

To see how the encapsulated context acts, we can investigate the output of the following example:

app.addHook('onRoute', buildHook('root')) // [1]
app.register(async function pluginOne(pluginInstance, opts)
  pluginInstance.addHook('onRoute', buildHook('pluginOne'))
    // [2]
  pluginInstance.get('/one', async () => 'one')
app.register(async function pluginTwo(pluginInstance, opts {
  pluginInstance.addHook('onRoute', buildHook('pluginTwo'))
    // [3]
  pluginInstance.get('/two', async () => 'two')
  pluginInstance.register(async function pluginThree(
  subPlugin, opts) {
    subPlugin.addHook('onRoute', buildHook('pluginThree'))
      // [4]
    subPlugin.get('/threee', async () => 'three')
function buildHook(id) {
  return function hook(routeOptions) {
    console.log(`onRoute ${id} called from ${routeOptions

Running the preceding code will execute [2] and [4] just one time, because inside pluginOne and pluginThree, only one route has been registered, and each plugin has registered only one hook. The onRoute hook [1] is executed three times, instead. This happens because it has been added to the app instance, which is the parent scope of all the plugins. For this reason, the root hook will listen to the events of its context and to the children’s ones.

This feature comes with an endless list of benefits that you will “get to know” through this book. To better explain the bigger advantage of this feature, imagine every plugin as an isolated box that may contain other boxes, and so on, where the Root application instance is the primary container of all the plugins. The previous code can be schematized in this diagram:

Figure 1.2 – Encapsulated contexts

Figure 1.2 – Encapsulated contexts

The request is routed to the right endpoint (the square in the diagram), and it will trigger all the hooks registered on each plugin instance that include the destination handler.

Every box is self-contained, and it won’t affect the behavior of its other siblings, thus giving you the certainty that no issue affects parts of the application other than the one where it occurred. Furthermore, the system only executes the hook functions your routes need! This allows you and your team to work on different parts of the application without affecting each other or causing side effects. Furthermore, the isolation will give you a lot more control over what is happening at your endpoints. Just to give you an example: you can add a dedicated database connection for hot-paths in your code base without extra effort!

This plugin example has shown more clearly the Fastify plugin system in action. It should help you understand the difference between a root application instance and plugin instances. You now have an idea of how powerful the plugin system is and of the benefits it implements by design:

  • Encapsulation: All the hooks, plugins, and decorators added to the plugin are binded to the plugin context
  • Isolation: Every plugin instance is self-contained and doesn’t modify sibling plugins
  • Inheritance: A plugin inherits the configuration of the parent plugin

The plugin system will be discussed in depth in Chapter 2.

Now, we are ready to explore how to manage the different configuration types a Fastify application needs to work correctly.