Reader small image

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

Product typeBook
Published inJun 2023
Reading LevelBeginner
PublisherPackt
ISBN-139781800563582
Edition1st Edition
Languages
Tools
Right arrow
Authors (3):
Manuel Spigolon
Manuel Spigolon
author image
Manuel Spigolon

Manuel Spigolon is a Senior Backend Developer at Near Form. He is one of core maintainers on the Fastiy team. Manuel has developed and maintained a complex API that serves more than 10 millions world wide.
Read more about Manuel Spigolon

Maksim Sinik
Maksim Sinik
author image
Maksim Sinik

Maksim Sinik is a senior engineering manager and a core maintainer of the Fastify framework. He has a decade of experience as a Node.js developer with a strong interest in backend scalability. He designed the architecture and led the development of several service-based Software-as-a-Service (SaaS) platforms across multiple industries that process hundreds of thousands of requests.
Read more about Maksim Sinik

Matteo Collina
Matteo Collina
author image
Matteo Collina

Matteo Collina is the co-founder and CTO of Platformatic who has the goal of removing all friction from backend development. He is also a prolific open source author in the JavaScript ecosystem, and the modules he maintains are downloaded more than 17 billion times a year. Previously, he was the chief software architect at NearForm, the best professional services company in the JavaScript ecosystem. In 2014, he defended his Ph.D. thesis titled Application Platforms for the Internet of Things. Matteo is a member of the Node.js Technical Steering Committee, focusing on streams, diagnostics, and HTTP. He is also the author of the fast logger, Pino, and the Fastify web framework. Matteo is a renowned international speaker after more than 60 conferences, including OpenJS World, Node.js Interactive, NodeConf.eu, NodeSummit, JSConf.Asia, WebRebels, and JsDay, to name just a few. Since August 2023, he also serves as a community director on the OpenJS Foundation. In the summer, he loves sailing the Sirocco.
Read more about Matteo Collina

View More author details
Right arrow

Working with Routes

Applications would not exist without routes. Routes are the doors to those clients that need to consume your API. In this chapter, we will present more examples, focusing on how to become more proficient at managing routes and keeping track of all our endpoints. We will cover all the possibilities that Fastify offers to define new endpoints and manage the application without giving you a headache.

It is worth mentioning that Fastify supports async/await handlers out of the box, and it is crucial to understand its implications. You will look at the difference between sync and async handlers, and you will learn how to avoid the major pitfalls. Furthermore, we will learn how to handle URL parameters, the HTTP request’s body input, and query strings too.

Finally, you will understand how the router works in Fastify, and you will be able to control the routing to your application’s endpoint as never before.

In this chapter, we will cover the following...

Technical requirements

As mentioned in the previous chapters, you will need the following:

  • A working Node.js 18 installation
  • A text editor to try the example code
  • An HTTP client to test out code such as CURL or Postman

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

Declaring API endpoints and managing the errors

An endpoint is an interface that your server exposes to the outside, and every client with the coordinates of the route can call it to execute the application’s business logic.

Fastify lets you use the software architecture you like most. In fact, this framework doesn’t limit you from adopting Representation State Transfer (REST), GraphQL, or simple Application Programming Interfaces (APIs). The first two architectures standardize the following:

  • The application endpoints: The standard shows you how to expose your business logic by defining a set of routes
  • The server communication: This provides insights into how you should define the input/output

In this chapter, we will create simple API endpoints with JSON input/output interfaces. This means that we have the freedom to define an internal standard for our application; this choice will let us focus on using the Fastify framework instead of following...

Routing to the endpoint

Routing is the phase where Fastify receives an HTTP request, and it must decide which handler function should fulfill that request. That’s it! It seems simple, but even this phase is optimized to be performant and to speed up your server.

Fastify uses an external module to implement the router logic called find-my-way (https://github.com/delvedor/find-my-way). All its features are exposed through the Fastify interface so that Fastify will benefit from every upgrade to this module. The strength of this router is the algorithm implemented to find the correct handler to execute.

The router under the hood

You might find it interesting that find-my-way implements the Radix-tree data structure, starting from the route’s URLs. The router traverses the tree to find the matched string URL whenever the server receives an HTTP request. Every route, tracked into the tree, carries all the information about the Fastify instance it belongs to.

During...

Reading the client’s input

Every API must read the client’s input to behave. We already mentioned the four HTTP request input types, which are supported by Fastify:

  • The path parameters are positional data, based on the endpoint’s URL format
  • The query string is an additional part of the URL the client adds to provide variable data
  • The headers are additional key:value pairs that pair information passing between the client and the server
  • The body is the request payload that contains the client’s data submission

Let’s take a look at each in more detail.

The path parameters

The path parameters are variable pieces of a URL that could identify a resource in our application server. We already covered this aspect in Chapter 1, so we will not repeat ourselves. Instead, it will be interesting to show you a new useful example that we haven’t yet covered; this example sets two (or more) path parameters:

app.get(&apos...

Managing the route’s scope

In Fastify, an endpoint has two central aspects that you will set when defining a new route:

  1. The route configuration
  2. The server instance, where the route has been registered

This metadata controls how the route behaves when the client calls it. Earlier in this chapter, we saw the first point, but now we must deepen the second aspect: the server instance context. The route’s scope is built on top of the server’s instance context where the entry point has been registered. Every route has its own route scope that is built during the startup phase, and it is like a settings container that tracks the handler’s configuration. Let’s see how it works.

The route server instance

When we talk about the route’s scope, we must consider the server instance where the route has been added. This information is important because it will define the following:

  • The handler execution context
  • The request...

Adding new behaviors to routes

At the beginning of this chapter, we learned how to use the routeOptions object to configure a route, but we did not talk about the config option!

This simple field gives us the power to do the following:

  • Access the config in the handler and hook functions
  • Implement the Aspect-Oriented Programming (AOP) that we are going to see later

How does it work in practice? Let’s find out!

Accessing the route’s configuration

With the routerOption.config parameter, you can specify a JSON that contains whatever you need. Then, it is possible to access it later within the Request component in the handlers or hooks’ function through the context.config field:

async function operation (request, reply) {
  return request.context.config
}
app.get('/', {
  handler: operation,
  config: {
    hello: 'world'
  }
})

In this way, you can create...

Summary

This chapter has explained how routing works in Fastify, from route definition to request evaluation.

Now, you know how to add new endpoints and implement an effective handler function, both async or sync, with all the different aspects that might impact the request flow. You know how to access the client’s input to accomplish your business logic and reply effectively with a success or an error.

We saw how the server context could impact the route handler implementation, executing the hooks in that encapsulated context and accessing the decorators registered. Moreover, you learned how to tweak the route initialization by using the onRoute hook and the route’s config: using Fastify’s features together gives us new ways to build software even more quickly!

The routing has no more secrets for you, and you can define a complete set of flexible routes to evolve thanks to the constraints and manage a broad set of real-world use cases to get things done...

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 2023Publisher: PacktISBN-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.
undefined
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

Authors (3)

author image
Manuel Spigolon

Manuel Spigolon is a Senior Backend Developer at Near Form. He is one of core maintainers on the Fastiy team. Manuel has developed and maintained a complex API that serves more than 10 millions world wide.
Read more about Manuel Spigolon

author image
Maksim Sinik

Maksim Sinik is a senior engineering manager and a core maintainer of the Fastify framework. He has a decade of experience as a Node.js developer with a strong interest in backend scalability. He designed the architecture and led the development of several service-based Software-as-a-Service (SaaS) platforms across multiple industries that process hundreds of thousands of requests.
Read more about Maksim Sinik

author image
Matteo Collina

Matteo Collina is the co-founder and CTO of Platformatic who has the goal of removing all friction from backend development. He is also a prolific open source author in the JavaScript ecosystem, and the modules he maintains are downloaded more than 17 billion times a year. Previously, he was the chief software architect at NearForm, the best professional services company in the JavaScript ecosystem. In 2014, he defended his Ph.D. thesis titled Application Platforms for the Internet of Things. Matteo is a member of the Node.js Technical Steering Committee, focusing on streams, diagnostics, and HTTP. He is also the author of the fast logger, Pino, and the Fastify web framework. Matteo is a renowned international speaker after more than 60 conferences, including OpenJS World, Node.js Interactive, NodeConf.eu, NodeSummit, JSConf.Asia, WebRebels, and JsDay, to name just a few. Since August 2023, he also serves as a community director on the OpenJS Foundation. In the summer, he loves sailing the Sirocco.
Read more about Matteo Collina