Fastify fundamentals

Intermediate · 30 min

Fastify 5 basics, with JSON-schema validation and serialization, encapsulated plugins, decorators, lifecycle hooks, built-in logging and graceful shutdown.

Before thisExpress error handling and async routes

TomDoesTech · 30 min

Fastify fundamentals

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by TomDoesTechReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Fastify is built around schemas and plugins. A JSON Schema on a route validates the request and, for responses, drives a fast serializer that also strips fields you did not declare.
  • Everything is a plugin, and `register` creates an encapsulated scope: hooks, decorators and routes added inside a plugin are invisible to the parent and siblings unless the plugin is wrapped with `fastify-plugin`.
  • Lifecycle hooks (`onRequest`, `preHandler`, `onSend`, `onResponse`, and others) replace Express-style middleware as the main extension point, and can be attached to one plugin scope.
  • Handlers can be `async` and return their value, or throw. There is no `next`. Call `setErrorHandler` before registering the routes it should cover: handlers are bound at registration time.
  • Fastify has a built-in pino logger (`logger: true`), `app.inject()` for testing without a socket, and `app.close()` for graceful shutdown.

What Fastify optimises for

Express gives you a router and a middleware chain, and leaves the rest to you. Fastify makes more decisions in advance. It assumes you describe routes with schemas, split the app into plugins, and use hooks at defined points of the request lifecycle. In exchange it can validate and serialize faster, log in a structured way by default, and keep large codebases tidy. It is built by Node core contributors (Matteo Collina is a maintainer) and its current major is Fastify 5.

Routes and schemas

import Fastify from 'fastify';
const app = Fastify({ logger: { level: 'warn' } });

const userSchema = {
  type: 'object',
  properties: { id: { type: 'integer' }, name: { type: 'string' } },
  required: ['id', 'name'],
};

app.get('/users/:id', {
  schema: {
    params: { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'] },
    response: { 200: userSchema },
  },
}, async (req, reply) => {
  const user = app.db.users.get(req.params.id);
  if (!user) return reply.code(404).send({ error: 'Not found' });
  return { ...user, passwordHash: 'should-not-leak' };
});

The handler is async and just returns the value; there is no res.json and no next. params.id is coerced to an integer before the handler runs: /users/abc returned 400 with params/id must be integer. And the response schema is a filter: passwordHash never reached the client in my run (Fastify 5.12). The request, response, body and query can each have a schema, so the validation lives in data, not in a hand-written middleware like the one in the Express REST lesson.

Plugins and encapsulation

Everything in Fastify is added with register, and each registered plugin gets its own scope:

await app.register(async (admin) => {
  admin.addHook('preHandler', async (req, reply) => {
    if (req.headers['x-admin'] !== 'yes') return reply.code(403).send({ error: 'forbidden' });
  });
  admin.get('/stats', async () => ({ users: app.db.users.size }));
}, { prefix: '/admin' });

The hook applies only to routes in this plugin, and the routes are mounted under /admin. That is the equivalent of an Express router with its own middleware, but enforced by the scope: siblings and the parent cannot see inside. To share something upward, such as a database connection, wrap the plugin with fastify-plugin, which opts out of encapsulation:

import fp from 'fastify-plugin';

await app.register(fp(async (instance) => {
  instance.decorate('db', { users: new Map([[1, { id: 1, name: 'Ada' }]]) });
  instance.decorateRequest('startedAt', 0);
}));

decorate adds a property to the instance, and decorateRequest and decorateReply add one to each request or reply object, declared up front so the shape stays stable for V8. Forgetting fp is the most common first confusion: without it, app.db is undefined outside the plugin.

Hooks

Hooks run at fixed stages: onRequest, preParsing, preValidation, preHandler, preSerialization, onSend, onResponse, and onError. Use them for what you would use middleware for in Express:

app.addHook('onRequest', async (req) => { req.startedAt = Date.now(); });
app.addHook('onSend', async (req, reply, payload) => {
  reply.header('x-took-ms', String(Date.now() - req.startedAt));
  return payload;
});

A preHandler hook that sends a reply (as in the admin example) stops the request; an async hook just returns to continue. Returning from the hook, instead of calling a next, is the same promise-first style as Express 5’s handlers.

Errors, logging and shutdown

app.setErrorHandler((err, req, reply) => {
  if (err.validation) return reply.code(400).send({ error: 'Validation failed', details: err.validation.map((v) => v.message) });
  req.log.error(err);
  reply.code(err.statusCode ?? 500).send({ error: 'Internal Server Error' });
});

Order matters here, and I found it by running it. With setErrorHandler called after the routes, validation errors still produced Fastify’s default body; moving the call before the routes made them use the custom handler. Routes bind their handler when registered. req.log is a pino logger with the request ID attached (logging with pino). For tests, await app.inject({ method: 'GET', url: '/users/1' }) runs a request through the full lifecycle without opening a port. For shutdown, await app.close() stops accepting connections and waits for in-flight requests; call it from a SIGTERM handler.

What the video covers

TomDoesTech’s “Learn Just Enough Fastify to be Productive” (February 2023, 30 min) is chaptered: intro, the basics (1:46), graceful shutdowns (4:17), plugins (8:41), decorators (13:13), lifecycle hooks (19:18), validation (22:27) and a bonus (25:51). That is nearly this lesson’s list, which is why I picked it. It is from the Fastify 4 era, so version details differ in places (Fastify 5 requires Node 20+ and tightens a few APIs), though the concepts are unchanged. I could not read a transcript. The response-schema filtering, the setErrorHandler ordering and the inject example are from this page, run on Fastify 5.

Where this fits

Fastify is an alternative to the Express path on the same http foundation. For a more structured, opinionated framework with dependency injection, see NestJS, which can itself run on Fastify.

Check yourself

  1. 01Your route's response schema lists `id` and `name`, but the handler returns `{ id, name, passwordHash }`. What does the client receive?

    Only `id` and `name`. Fastify serializes responses with the schema, and properties not listed are dropped. In a test, `passwordHash` never appeared. That protects against leaking fields by accident, and it is also why schemas make serialization faster.

  2. 02You register a plugin that calls `decorate('db', ...)`, but `app.db` is undefined in your routes. What went wrong?

    Plugins are encapsulated. A decoration made inside a registered plugin is only visible inside that plugin's scope and its children. Wrap the plugin in `fastify-plugin` (`fp`) to opt out of encapsulation so the decoration lands on the parent instance.

  3. 03You call `app.setErrorHandler(...)` after your routes and validation failures still use Fastify's default body. Why?

    Route handlers bind the error handler at the time the route is registered, so later `setErrorHandler` calls only affect routes added afterwards. In a test, moving the call before the routes changed the 400 body to the custom format. Set it early, in the plugin that owns the routes.

  4. 04Why does Fastify advertise better performance than Express?

    Mostly design choices: compiled schema validation (Ajv) and compiled serializers instead of generic `JSON.stringify` on arbitrary objects, a fast router, minimal per-request work, and async-first handlers. The gap shrinks when your handler is dominated by database or network time.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark