Fastify Tutorial
Learn Fastify step by step: 39 lessons in 9 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
Getting Started
- What Is Fastify? Meet Fastify, the low-overhead Node.js web framework: what it is, why it is fast, how it compares with Express, and what you will build in this course.
- Your First Fastify Server Create and start your first Fastify server: install the package, write a route, call listen with port and host, handle startup errors and shut down cleanly.
- How a Request Flows Through Fastify Understand the Fastify request lifecycle and its core objects: the instance, request, reply, hooks, decorators and plugins, with runnable examples of the order.
- Server Options and Logging Configure Fastify with server options (logger, bodyLimit, trustProxy, timeouts, request ids) and learn structured Pino logging: levels, child loggers and redaction.
- Project Structure and Configuration Organize a Fastify project: separate app and server files, load validated configuration from environment variables, use fastify-cli, and keep the app testable.
Routes and Handlers
- Routing Basics in Fastify Learn Fastify routing: shorthand methods, the full route() declaration, route options, multiple methods, route priority, 404 handling and duplicate-route errors.
- Route Parameters and Query Strings Read dynamic URL segments and query strings in Fastify: request.params, request.query, wildcards, repeated keys, decoding, and how types are coerced.
- The Fastify Request Object Tour the Fastify request object: reading the JSON body, headers, params, query, method, URL, id and client IP, plus body parsing errors and content types.
- The Fastify Reply Object Master the Fastify reply object: status codes, headers, content types, send() with strings, objects and buffers, redirects, and the async return rules.
- Async Handlers and Error Handling Handle errors in Fastify: throw from async handlers, set statusCode, write custom error classes, use setErrorHandler, hide internal details and log properly.
Schemas and Validation
- JSON Schema Basics in Fastify Learn how Fastify uses JSON Schema to validate requests: types, required fields, constraints, defaults, coercion and what a failed validation looks like.
- Validating Request Parts Validate every part of a Fastify request: body, params, querystring and headers. Learn the error format, attachValidation and handling errors in one place.
- Shared Schemas and $ref Stop repeating yourself: register shared JSON Schemas with addSchema, reference them with $ref, build create/update variants and scope schemas to plugins.
- Validation Errors and Formatting Customize Fastify validation errors: read error.validation, use schemaErrorFormatter, return field-level messages, tune Ajv options and swap the validator.
- Type Providers and TypeBox Get static TypeScript types from your Fastify JSON Schemas: type providers, TypeBox, Static types, response typing and how it compares with Zod.
Plugins and Encapsulation
- Plugins and register() Everything in Fastify is a plugin. Learn how to write one, pass it options, give its routes a prefix, understand load order and split an app into modules.
- Encapsulation Explained Understand Fastify encapsulation: how each plugin gets its own scope, what children inherit, why siblings cannot see each other and how to scope hooks safely.
- Decorators in Depth Add your own properties and helpers to Fastify with decorate, decorateRequest and decorateReply. Learn the rules, the this keyword, request-level state and pitfalls.
- fastify-plugin and Sharing Across Scopes Learn when and how to use fastify-plugin to break encapsulation on purpose: sharing a database, config or auth across plugins, plugin metadata and common pitfalls.
- Official Plugins and Autoload A tour of the official Fastify plugin ecosystem (cors, helmet, jwt, env, sensible, static and more), how to register them, and how autoload wires folders into prefixes.
Hooks and Lifecycle
- The Fastify Request Lifecycle Follow one request through Fastify from routing to onResponse: every stage, what runs in it, how errors and early replies change the path, with runnable examples.
- Application Hooks: onReady, onClose, onRoute and Friends Learn Fastify application hooks: onRoute, onRegister, onReady, onListen, preClose and onClose. Open and close database pools, inspect routes and clean up safely.
- Request and Reply Hooks in Practice Use Fastify request and reply hooks the right way: timing, request IDs, route-level hooks, response envelopes, headers in onSend, and how plugin scope limits hooks.
- Error Handling and Not Found Routes Handle errors in Fastify: throw and send errors, custom error classes, setErrorHandler, validation errors, onError, setNotFoundHandler and safe 500 responses.
Serialization and Performance
- Response Serialization and Schemas Understand Fastify response serialization: response schemas, per-status schemas, stripping private fields, type coercion, required properties and custom serializers.
- Content-Type Parsers, Streams and Custom Replies Teach Fastify new body formats with addContentTypeParser, understand body limits and 415 errors, and send text, buffers, streams and redirects with the reply API.
- Performance Tuning Fastify Applications Why Fastify is fast and how to keep it fast: protect the event loop, compile serializers, cut logging cost, use caching headers, pools, clustering and benchmarks.
- Logging with Pino in Fastify Use Fastify's built-in Pino logger well: log levels, structured fields, child loggers, request IDs, redacting secrets, serializers and pretty output for development.
- Caching, ETags and Compression Make Fastify responses cheaper: Cache-Control headers, ETags with 304 answers, a small in-memory cache with expiry, and when to compress responses with gzip.
Authentication and Security
- JWT Authentication with Fastify Understand JSON Web Tokens from the inside, sign and verify an HS256 token with node:crypto, protect Fastify routes with an authenticate hook, and avoid common JWT mistakes.
- Passwords, Sessions and Cookies Hash passwords with scrypt, keep login state in signed cookies or server sessions, set HttpOnly and SameSite flags, and stop CSRF with tokens in Fastify apps.
- Security Headers, CORS and Rate Limiting Harden a Fastify API: set security headers like Helmet, configure CORS and preflight correctly, and add a rate limiter that answers 429 with Retry-After.
- Authorization, Input Hardening and Secrets Go beyond login: enforce ownership and roles, stop mass assignment and IDOR bugs, limit body size, validate environment secrets and keep them out of logs in Fastify.
Testing and Deployment
- Testing Fastify Apps with inject Test Fastify routes without opening a port: build the app in a factory, call app.inject, assert status, headers and JSON, and run it all with node:test.
- Testing Plugins, Hooks and Fakes Test Fastify plugins and hooks in isolation, replace the database, clock and mailer with fakes through dependency injection, and add a few real-socket end-to-end tests.
- Deploying Fastify: Docker, Environments, Shutdown Ship a Fastify app: listen on 0.0.0.0, configure through environment variables, build a small Docker image, add health checks and shut down gracefully on SIGTERM.
Projects and Practice
- Project: Notes API Build a complete notes REST API in the Fastify style: routes, JSON schema validation, pagination, search, error handling, plugins and a test suite using inject.
- Project: Authenticated Bookmarks API Combine registration with hashed passwords, JWT login, per-user bookmarks, ownership checks, rate limiting and an inject test suite into one secure Fastify-style API.
- Practice: Exercises and Interview Questions Practice Fastify with hands-on exercises on hooks, errors, validation, auth and testing, each with a runnable solution, plus common interview questions with short answers.