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

Preface

Fastify is a plugin-based web framework designed to be highly performant. It fosters code reuse, thereby improving your time to market.

This book is a complete guide to server-side app development in Fastify, written by the core contributors of Fastify. The book starts from the core concepts, continuing with a real-world project and even touching on more advanced topics to enable you to build highly maintainable and scalable backend applications. You’ll learn how to develop real-world RESTful applications from design to deployment, and build highly reusable components.

By the end of this book, you’ll be able to design, implement, deploy, and maintain an application written in Fastify, and you’ll also have the confidence you need to develop plugins and APIs in Fastify to contribute back to the Fastify and open source communities.

Who this book is for

This book is for mid-to expert-level backend web developers who have already used other backend web frameworks and have worked with HTTP protocol and its peculiarities. Developers looking to migrate to Fastify and learn how it can be a good fit for their next project, avoid architecture pitfalls, and build highly responsive and maintainable API servers will also find this book useful. The book assumes knowledge of JavaScript programming, Node.js, and backend development.

What this book covers

Chapter 1, What Is Fastify?, introduces Fastify, its purpose, and how it can speed up the development process. It covers the basic syntax for starting an application, adding endpoints, and configuring the server.

Chapter 2, The Plugin System and the Boot Process, explains the importance of Fastify plugins for developers, highlighting their role in achieving reusability, code sharing, and proper encapsulation between Fastify instances. The chapter focuses on the declaration and implementation of a simple plugin, gradually adding more layers to explore their interaction and dependency management.

Chapter 3, Working with Routes, covers the importance of routes in applications and how to manage them effectively with Fastify. It explains how to handle URL parameters, body, and query strings and how the router works in Fastify. The chapter also highlights the significance of Fastify’s support for async/await handlers and provides tips for avoiding pitfalls when using them.

Chapter 4, Exploring Hooks, explains how Fastify is different from other web frameworks because it uses hooks instead of middleware. Mastering these hooks is essential for building stable and production-ready server applications. The chapter provides an overview of the hooks and the life cycle of Fastify applications.

Chapter 5, Exploring Validation and Serialization, focuses on implementing secure endpoints with input validation and optimizing them with the serialization process in Fastify. The chapter emphasizes the importance of using Fastify’s built-in tools to control and adapt the default setup to suit your application’s logic. You will learn how to configure and use Fastify components to create straightforward APIs that clients can easily consume.

Chapter 6, Project Structure and Configuration Management, guides you through creating a real-world RESTful cloud-native application, putting into action what you’ve learned in previous chapters. You’ll build a solid project structure that can be reused for future projects, utilizing community packages and creating custom plugins as needed.

Chapter 7, Building a RESTful API, focuses on building a real-world Fastify application by defining routes, connecting to data sources, implementing business logic, and securing endpoints. The chapter will cover essential parts of the application, including implementing routes, connecting to data sources, securing endpoints, and applying the don’t repeat yourself (DRY) principle to make code more efficient.

Chapter 8, Authentication and File Handling, covers user authentication and file handling in our application. We’ll begin by implementing a reusable JWT authentication plugin that will handle user authentication, sessions, and authorization. We’ll also explore decorators to expose authenticated user data in route handlers. Next, we’ll develop a plugin to handle file import/export in CSV format for user to-do tasks.

Chapter 9, Application Testing, focuses on testing in Fastify. It covers the integrated testing tools and how to use them. It also explains how to run tests in parallel without requiring an HTTP server.

Chapter 10, Deployment and Process Monitoring for a Healthy Application, explores different deployment options for our Fastify API, focusing on a monolith deployment using Docker, MongoDB, and Fly.io. We will also learn about Node.js metrics and how to monitor the health of our server using Prometheus and Grafana.

Chapter 11, Meaningful Application Logging, explains how to implement effective logging in your Fastify application to keep track of what’s happening and monitor its performance. You’ll discover how to set up a logging configuration that captures all the necessary information without logging sensitive data and how to interpret and analyze logs to identify and troubleshoot issues.

Chapter 12, From a Monolith to Microservices, discusses restructuring a monolithic application into multiple modules to minimize conflicts between different teams. The chapter discusses adding new routes without increasing project complexity, splitting the monolith into microservices, and using an API gateway to route relevant calls. The chapter also covers logging, monitoring, error handling, and addressing operator questions.

Chapter 13, Performance Assessment and Improvement, focuses on optimizing the performance of your Fastify application. You will learn how to measure your code’s performance to avoid slow performance, identify bottlenecks in your code, and prevent production issues. You will be introduced to an instrumentation library to help you analyze how your server reacts to high-volume traffic. Additionally, you will learn how to interpret the measurements and take action to keep your server’s performance healthy.

Chapter 14, Developing a GraphQL API, explains how to incorporate GraphQL into your Fastify application using a specialized plugin. As GraphQL becomes increasingly popular, more and more APIs are being built with this query language. By using Fastify’s unique architecture and avoiding common mistakes, you can take full advantage of GraphQL in your application.

Chapter 15, Type-Safe Fastify, explores how Fastify’s built-in TypeScript support can help developers write more robust and maintainable applications. With compile-time type safety and better code completion, type inference, and documentation, developers can catch errors early in the development process and avoid unexpected runtime errors, leading to more stable and reliable applications. Using TypeScript with Fastify can also provide an extra layer of protection to code, making deployments safer and giving developers more confidence when developing code.

To get the most out of this book

To fully grasp the concepts discussed in this book, it is assumed that you have a basic understanding of the HTTP protocol, including the different methods and status codes. Additionally, you are expected to be familiar with running a Node.js application and can install and manage Node.js packages using npm.

Software/hardware covered in the book

Operating system requirements

Fastify 4

Windows, macOS, or Linux

Additionally, since we will be using containerization extensively throughout the book, it is recommended to have Docker installed on your machine before starting.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Accelerating-Server-Side-Development-with-Fastify. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://packt.link/df1Dm

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “The getSchemas() method returns a JSON key-value pair where the key is the schema’s $id and the value is the JSON schema itself.”

A block of code is set as follows:

{
  "id": 1,
  "name": "Foo",
  "hobbies": [ "Soccer", "Scuba" ]
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

"test": "tap --before=test/run-before.js test/**/**.test.js --after=test/run-after.js --no-check-coverage",
"test:coverage": "tap --coverage-report=html --before=test/run-before.js test/**/**.test.js --after=test/run-after.js",

Any command-line input or output is written as follows:

<absolute URI>#<local fragment>

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “It is crucial to keep in mind that you should take care of the response status code when you implement your error handler; otherwise, it will be 500 – Server Error by default.”

Tips or Important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at customercare@packtpub.com and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

  1. Scan the QR code or visit the link below

https://packt.link/free-ebook/9781800563582

2. Submit your proof of purchase

3. That’s it! We’ll send your free PDF and other benefits to your email directly

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