Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 39 ยท Plugins and Encapsulation

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.

You rarely need to write everything yourself. Fastify ships a small core (routing, hooks, validation, logging) and leaves the rest to plugins, with a family of officially maintained ones under the @fastify/ npm scope. They all follow the rules from this chapter: they are functions that receive an instance and options, and most are wrapped with fastify-plugin so their decorators reach your routes.

None of these packages can be installed on this site (the runner has no npm), so this lesson shows the real registration code as read-only snippets and uses small stand-ins to demonstrate the two ideas that matter most: configuration checked at start-up and autoloading a folder of plugins.

A tour of the official plugins

Package What it gives you
@fastify/cors CORS headers so browsers on other origins can call your API
@fastify/helmet A set of security headers (CSP, HSTS, X-Content-Type-Options, ...)
@fastify/rate-limit Per-client request limits with 429 Too Many Requests
@fastify/jwt Sign and verify JSON Web Tokens; request.jwtVerify()
@fastify/cookie Read and set cookies; signed cookies
@fastify/session Server-side sessions on top of cookies
@fastify/sensible Helpers like reply.notFound() and app.httpErrors.badRequest()
@fastify/static Serve files from a folder (reply.sendFile())
@fastify/multipart File uploads and multipart/form-data bodies
@fastify/formbody Parse application/x-www-form-urlencoded bodies
@fastify/env Load and validate environment variables with a JSON Schema
@fastify/swagger + swagger-ui Generate OpenAPI documentation from your route schemas
@fastify/under-pressure Return 503 when the event loop or memory is overloaded
@fastify/compress gzip / brotli response compression
@fastify/websocket WebSocket routes
@fastify/autoload Register every plugin and route file in a folder

Registration is always the same, whatever the plugin:

JavaScript
import Fastify from 'fastify';
import cors from '@fastify/cors';
import helmet from '@fastify/helmet';
import rateLimit from '@fastify/rate-limit';

const app = Fastify({ logger: true });

await app.register(helmet);
await app.register(cors, { origin: ['https://app.example.com'], credentials: true });
await app.register(rateLimit, { max: 100, timeWindow: '1 minute' });

The second argument is the plugin's options. Because these plugins use fp, they apply to the scope in which you register them, so put the global ones on the root, before your routes (remember the order rules from the fastify-plugin lesson). You will use several of them in the authentication and security chapter.

Choosing and vetting plugins

  • Prefer @fastify/* for core needs: they track Fastify's releases and security fixes.
  • Check the fastify range in a community plugin's metadata (a plugin built for Fastify 3 will refuse to load on 5, by design).
  • Keep the plugin list short. Every plugin adds an upgrade path. If a helper is twenty lines, write it yourself as a local plugin.
  • Scope plugins narrowly when only part of the app needs them: register @fastify/multipart inside the upload routes' plugin instead of on the root.

Configuration that fails at start-up

@fastify/env reads process.env and validates it with a JSON Schema, then decorates the app with app.config. The idea is more important than the package: the server must refuse to start with bad configuration, not discover it on request number one hundred.

JavaScript
import env from '@fastify/env';

await app.register(env, {
  confKey: 'config',
  schema: {
    type: 'object',
    required: ['DATABASE_URL'],
    properties: {
      DATABASE_URL: { type: 'string' },
      PORT: { type: 'integer', default: 3000 },
    },
  },
});

You can see the same idea with the schema vocabulary you learned in the previous chapter. This stand-in plugin validates a plain object (a fake environment) and fails the start-up when something is wrong:

Node.js A config plugin that refuses to start with bad settings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The three runs show a normal start, a start that uses the default PORT, and a start refused because two settings are missing or invalid. In production this is a crash-loop with a readable message in the logs, which is exactly what you want from a bad deployment.

Autoload: let the folder structure do the wiring

When an app grows past a dozen plugins, app.register(...) lines pile up. @fastify/autoload registers everything in a directory for you:

JavaScript
import autoLoad from '@fastify/autoload';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const here = dirname(fileURLToPath(import.meta.url));

// 1. Shared infrastructure: db.js, auth.js, ... (use fastify-plugin inside them)
await app.register(autoLoad, { dir: join(here, 'plugins') });

// 2. Feature routes: each sub-folder becomes a prefix
await app.register(autoLoad, { dir: join(here, 'routes'), options: { prefix: '/api' } });

With this folder layout:

TEXT
src/
  plugins/
    db.js          -> registered first, no prefix
    auth.js
  routes/
    users/
      index.js     -> /api/users...
    orders/
      index.js     -> /api/orders...
    health.js      -> /api/health

The rules are simple: files in the loaded directory are registered as plugins in alphabetical order; a sub-folder becomes a URL prefix named after the folder (routes/users becomes /users); index.js in a folder is that folder's main plugin; and a folder can contain a file with hooks that should apply to everything under it. Two options to know: dirNameRoutePrefix: false turns off folder-based prefixes, and ignorePattern skips test or helper files.

The following demo reproduces the idea with a virtual folder (an object that maps "file paths" to plugins), since the runner has no real files to load:

Node.js Autoload, simulated with a virtual folder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The plugin in plugins/ is shared (it uses fp), and each folder under routes/ became a prefix without a single hand-written register(..., { prefix }) line. Adding a new feature now means adding a folder.

Keeping an autoloaded app understandable

  • Split by role: plugins/ for infrastructure with fp, routes/ for encapsulated features, schemas/ for shared schemas.
  • Name files by purpose (users.js, auth.js): the file name often becomes the plugin name in logs.
  • Print the tree during development: app.printRoutes() and app.printPlugins() show what autoload actually did.
  • Test with inject. Autoload is not magic that needs a special test setup; build the app, call ready(), then inject requests.

Common mistakes

  • Registering a plugin that needs db before the autoload of plugins/. Load infrastructure first.
  • Putting tests or helpers inside an autoloaded folder without ignorePattern, so they get loaded as plugins.
  • Forgetting fp in files under plugins/. Their decorators then stay private to a child scope and routes cannot see them.
  • Trusting process.env directly in handlers. Validate configuration once, in a plugin, and read app.config.
  • Installing a plugin for every small need. Each one is code you must keep updated.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do most @fastify/* plugins use fastify-plugin?

    Without fp, a plugin's decorators and hooks would be trapped in a private child scope.
  2. 2. What should a server do when a required environment variable is missing?

    Validate configuration at start-up (for example with @fastify/env) so bad deployments fail fast and visibly.
  3. 3. With @fastify/autoload, what does a sub-folder like routes/users become by default?

    Autoload turns directory names into route prefixes, so every route in routes/users is mounted under /users.
  4. 4. Which plugin is the right choice to answer 429 when a client sends too many requests?

    @fastify/rate-limit limits requests per client and responds 429 Too Many Requests.

Summary

  • The @fastify/* packages (cors, helmet, rate-limit, jwt, cookie, sensible, static, multipart, env, swagger, autoload, ...) are ordinary plugins registered with app.register(plugin, options).
  • Register global plugins on the root before your routes; scope special ones (like multipart) to the feature that needs them.
  • Validate configuration at start-up so a bad deployment fails immediately (@fastify/env).
  • @fastify/autoload registers whole folders: plugins/ for shared infrastructure, routes/ for features with folder-name prefixes.
  • Keep the plugin list short and prefer official, version-checked packages.

Next: The Fastify Request Lifecycle