Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Accelerating Server-Side Development with Fastify

You're reading from  Accelerating Server-Side Development with Fastify

Product type Book
Published in Jun 2023
Publisher Packt
ISBN-13 9781800563582
Pages 406 pages
Edition 1st Edition
Languages
Authors (3):
Manuel Spigolon Manuel Spigolon
Profile icon Manuel Spigolon
Maksim Sinik Maksim Sinik
Profile icon Maksim Sinik
Matteo Collina Matteo Collina
Profile icon Matteo Collina
View More author details

Table of Contents (21) Chapters

Preface 1. Part 1:Fastify Basics
2. Chapter 1: What Is Fastify? 3. Chapter 2: The Plugin System and the Boot Process 4. Chapter 3: Working with Routes 5. Chapter 4: Exploring Hooks 6. Chapter 5: Exploring Validation and Serialization 7. Part 2:Build a Real-World Project
8. Chapter 6: Project Structure and Configuration Management 9. Chapter 7: Building a RESTful API 10. Chapter 8: Authentication, Authorization, and File Handling 11. Chapter 9: Application Testing 12. Chapter 10: Deployment and Process Monitoring for a Healthy Application 13. Chapter 11: Meaningful Application Logging 14. Part 3:Advanced Topics
15. Chapter 12: From a Monolith to Microservices 16. Chapter 13: Performance Assessment and Improvement 17. Chapter 14: Developing a GraphQL API 18. Chapter 15: Type-Safe Fastify 19. Index 20. Other Books You May Enjoy

Exploring Hooks

In this chapter, we will learn what makes Fastify different from the majority of other web frameworks. In fact, contrary to several other frameworks that have the concept of middleware, Fastify is based on hooks. They all have different use cases, and mastering their usage is key to developing stable and production-ready server applications.

Even if the topic is considered somehow complex, the goal of the subsequent sections is to give a good overview of how the Fastify framework “thinks” and build the right confidence in using these tools.

Before going into their details, though, we need to introduce another concept that makes everything even possible. Namely, we need to learn about the lifecycle of Fastify applications.

In this chapter, we will focus on these concepts:

  • What is a lifecycle?
  • Declaring hooks
  • Understanding the application lifecycle
  • Understanding the request and reply lifecycle

Technical requirements

To follow this chapter, you will need the following:

  • A text editor, such as VS Code
  • A working Node.js v18 installation
  • Access to a shell such as Bash or CMD
  • The curl command-line application

All the code snippets for this chapter are available on GitHub at https://github.com/PacktPublishing/Accelerating-Server-Side-Development-with-Fastify/tree/main/Chapter%204.

What is a lifecycle?

When talking about a lifecycle in the context of a framework, we refer to the order in which the functions are executed. The tricky part is that application developers write only a subset of its code while the rest is developed and bundled by the framework developers.

During the application execution, the function calls bounce between internal and user-written code, and it might be hard to follow what is going on. So, it comes naturally at this point that having deep knowledge of this subject is crucial.

The lifecycle depends on the architecture of the framework. Two well-known architectures are usually used to develop a web framework:

  • Middleware-based architecture: Thanks to its more manageable learning curve, this is the most known lifecycle architecture, but time has proved it to have some significant drawbacks. When working with this architecture, an application developer must care about the order of declaration of the middleware functions since...

Declaring hooks

In the previous section, we saw that a server-side application usually has two main lifecycles. So, being a hook-based web framework and following its philosophy of giving complete control to developers, Fastify emits a specific event every time it advances to the next phase. Furthermore, these phases follow a rigid and well-defined execution order. Knowing it enables us to add functionality at a specific point during the boot or the execution of our application.

One essential and beneficial side effect of this approach is that, as developers, we don’t care about the declaration order of our hooks since the framework guarantees that they will be invoked at the right moment in time.

The mechanism described works because Fastify, under the hood, defines a “hook runner” that runs the callback functions declared for every known event. As developers, we need a method to attach our hooks to the Fastify instance. The addHook hook allows us to do...

Understanding the application lifecycle

The application lifecycle covers the boot process and the execution of our application server. In particular, we refer to loading the plugins, adding routes, making the HTTP server run, and eventually closing it. Fastify will emit four different events, allowing us to interact with the behavior of every phase:

  • onRoute
  • onRegister
  • onReady
  • onClose

Now, for every event of the previous list, let’s check the respective callback signature and most common use cases.

The onRoute hook

The onRoute hook event is triggered every time a route is added to the Fastify instance. This callback is a synchronous function that takes one argument, commonly called routeOptions. This argument is a mutable object reference to the route declaration object itself, and we can use it to modify route properties.

This hook is encapsulated and doesn’t return any value. Therefore, one of the most common use cases is adding route...

Understanding the request and reply lifecycle

When executing a Fastify server application, the vast majority of the time is spent in the request-reply cycle. As developers, we define routes that the clients will call and produce a response based on the incoming conditions. In true Fastify philosophy, we have several events at our disposal to interact with this cycle. As usual, they will be triggered automatically by the framework only when needed. These hooks are fully encapsulated so that we can control their execution context with the register method.

As we saw in the previous section, we had four application hooks. Here, we have nine request and reply hooks:

  • onRequest
  • preParsing
  • preValidation
  • preHandler
  • preSerialization
  • onSend
  • onResponse
  • onError
  • onTimeout

Since they are part of the request/reply cycle, the trigger order of these events is crucial. Therefore, the first seven elements of the list are written from the first to the last...

Summary

In this chapter, we learned one of the Fastify concepts that make it different from most web frameworks. Even if it might be a new concept to many developers, mastering hooks will unleash the path to highly performant, maintainable, and reusable application components. In fact, contrary to middleware, when we define a hook, we are guaranteed that our code is executed only when it makes sense, boosting the application’s performance. Furthermore, having a well-defined order of execution can help with debugging and runtime checking.

In the next chapter, we will learn how to make user inputs safe and speed up our server thanks to validation and serialization.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Accelerating Server-Side Development with Fastify
Published in: Jun 2023 Publisher: Packt ISBN-13: 9781800563582
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}