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

Exploring Validation and Serialization

Fastify is secure and fast, but that doesn’t protect it from misuse. This chapter will teach you how to implement secure endpoints with input validation and make them faster with the serialization process.

This framework provides all the tools you need to take advantage of these two critical steps, which will support you while exposing straightforward API interfaces and enable your clients to consume them.

You will learn how to use and configure Fastify’s components in order to control and adapt the default setup to your application logic.

This is the learning path we will cover in this chapter:

  • Understanding validation and serialization
  • Understanding the validation process
  • Customizing the validator compiler
  • Managing the validator compiler
  • Understanding the serialization process

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 on GitHub at https://github.com/PacktPublishing/Accelerating-Server-Side-Development-with-Fastify/tree/main/Chapter%205.

Understanding validation and serialization

Fastify has been built with a focus on the developer’s experience, and on reducing the developer effort needed to draft a new project. For this reason, Fastify has built-in features to reduce the following burdens:

  • Validating the user’s input
  • Filtering the server’s output

The aim is to find solutions for and prevent the most common security attacks, such as code injection or sensitive data exposure. The answer is declaring the expected input and output data format for every route. Therefore, the validation and serialization processes have been introduced into the framework by design:

Figure 5.1 – The Validation and Serialization phases

Figure 5.1 – The Validation and Serialization phases

This preceding diagram shows the request lifecycle steps’ macro architecture, which you read about in detail in Chapter 4.

The Validation phase happens when the HTTP Request comes into the server. It allows you to approve...

Understanding the validation process

The validation process in Fastify follows the same logic to validate the incoming HTTP request parts. This business logic comprises two main steps, as we saw in Figure 5.2:

  • The schema compilation executed by the Validator Compiler
  • The validation execution

We will discuss these aspects one by one.

The validator compiler

Fastify doesn’t implement a JSON Schema interpreter itself. Still, it has integrated the Ajv (https://www.npmjs.com/package/ajv) module to accomplish the validation process. The Ajv integration into Fastify is implemented to keep it as fast as possible and support the encapsulation as well. You will always be able to change the default settings and provide a new JSON Schema interpreter to the application, but we will learn how to do it later, in the Managing the validator compiler section.

Ajv version

Fastify has included the Ajv module version 8. This is important to know when you need to search...

Customizing the validator compiler

Fastify exposes a lot of options to provide a flexible validation process and complete control of it. We are going to explore all the possible customizations one by one, so you will be a validator compiler guru by the end of this section! Let’s jump into this journey one step at a time!

Flow control

In the previous section, we mentioned the attachValidation route option – it’s time to look at an example (although you probably already know how to use it, thanks to the previous chapters):

app.get('/attach-validation', {
  attachValidation: true,
  schema: {
    headers: jsonSchemaHeaders
  },
  handler: (request, reply) => {
    reply.send(request.validationError)
  }
})

Adding the flag into the route option will prevent a validation error from being thrown. Instead, the validation execution process will be interrupted...

Managing the validator compiler

Fastify offers you the possibility to customize the validator compiler in two different manners:

  • Configuring the default Ajv validator compiler
  • Implementing a brand-new validator compiler, such as a new JSON Schema compiler module

These options give you total control over the validation process and the ability to react to every situation you may face, such as adopting a new validator compiler module or managing how the Ajv package processes the input data.

Configuring the default Ajv validator compiler

In the Understanding the Ajv configuration section, we saw the default Ajv settings and a link to its documentation to explore them all. If you find some useful options you would like to apply, you can set them during the Fastify instance instantiation:

const app = fastify({
  ajv: {
    customOptions: {
      coerceTypes: 'array',
    ...

Understanding the serialization process

Serialization is the process of transforming complex objects or primitive data into a valid data type that can be transmitted to the client. A valid data type is a String, a Stream, or a Buffer.

In the Understanding validation and serialization section, we introduced the concept of Fastify’s serialization process, which uses JSON schemas to adapt a response payload to a defined format. This is the only task that this process carries out. It doesn’t apply any sort of validation of the output. This is often confusing because the JSON Schema is associated with the validation phase. Therefore, it would be more appropriate to compare it to filter processing rather than to a validation.

The actors in action are quite similar to what we saw in the Building a new validator compiler section, with some additions. In the following diagram, Figure 5.5, we are going to present these additions, extending the Serialization box we saw in...

Summary

This chapter has followed a long path inside Fastify’s internals to unveil the JSON schema’s power. Now you understand why defining a JSON Schema is a critical phase in your application setup. It can be a hard task, but data validation and a fast response are the two main reasons to do this.

We have looked at the JSON Schema specification’s basics and how to use it in our routes, adopting the default Fastify components. We did not step back to configure these components, and now you have seen the whole process, you can control them to reach your goals.

It has not been easy. The concepts in this chapter are the most misused by developers that use Fastify. You did a great job, and I hope the diagrams have helped you follow the logic behind the validation and the serialization.

This chapter is the last theoretical one: congratulations! In many chapter’s sections, we read concepts that were already discussed in the previous chapters. This is...

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