Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

What Fastify is

Fastify is a web framework for Node.js used to write servers and JSON APIs. It handles request parsing, routes, data validation and sending replies, so you only write the code of your application. This course targets Fastify 5 and Node.js 22 or newer with ES modules (import and export).

What you need

You need Node.js 22 or newer and npm, which is installed with it. Check the versions in a terminal:

node -v
npm -v

If the first command shows a version below 22, install the current LTS version from nodejs.org.

Why Fastify is fast

Fastify's speed comes from several decisions:

DecisionWhat it gives
Fast route lookupThe address is matched against a tree, not against every route in turn
Response schemasJSON is built from a known structure instead of the generic JSON.stringify
The Pino loggerWriting logs barely slows the server down
PluginsCode is loaded once at startup, not on every request

For a small blog the speed difference is invisible. What matters more is that the same decisions make the code tidier: schemas check incoming data, and plugins split the application into independent parts.

Fastify and Express

If you know Express, a lot will look familiar: routes are also declared with app.get() and app.post(). The main differences:

  • a handler can simply return an object, and Fastify sends it as JSON;
  • asynchronous (async) handlers work without extra wrappers;
  • schema validation is built into the framework;
  • plugins and hooks are used instead of middleware.

The running example

Throughout the course you build a JSON API for a blog: posts and their comments. A client — a browser, a mobile app or another server — sends requests, and the API answers with JSON data:

GET    /posts              list of posts
GET    /posts/:id          one post
POST   /posts              new post
GET    /posts/:id/comments comments of a post

At first posts are kept in an array, later in an SQLite database.

Common mistake

Many examples online are written for Fastify 3 or 4 and for CommonJS (require). Some of them do not work in Fastify 5: for example, shorthand schemas without type: 'object' are no longer accepted. Check the version in examples and in package.json.

Thanks for reading!

Donate to the site — we work hard for you.