fastify-best-practise

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Fastify Best Practices

Fastify 最佳实践

A curated set of rules and patterns for building production-ready Fastify applications. Each rule includes incorrect and correct examples with explanations.
这是一套用于构建生产环境可用的Fastify应用的精选规则与模式。每条规则都包含错误示例、正确示例以及对应的解释。

How It Works

工作原理

  1. The agent identifies that the user is working with Fastify or asking about Fastify patterns
  2. The relevant rule file is loaded based on the topic (routes, validation, encapsulation, etc.)
  3. The agent applies the best practices from the rule when generating or reviewing code
  1. Agent识别到用户正在使用Fastify或询问Fastify相关模式
  2. 根据主题(路由、验证、封装等)加载对应的规则文件
  3. Agent在生成或评审代码时,应用规则中的最佳实践

Rules

规则

The rules are organized by topic in the
rules/
directory. Each rule follows a consistent format with impact rating, incorrect/correct examples, and references to official docs.
RuleFileImpactDescription
Configurationconfiguration.mdHIGHEnvironment config, logger setup, security options, and graceful shutdown
Create Servercreate-server.mdLOW-MEDIUMUse a
buildServer()
factory function for reusable, testable server setup
Create Plugincreate-plugin.mdLOW-MEDIUMEncapsulate reusable functionality in plugins with
fastify-plugin
Autoloadautoload.mdHIGHAutomatically load plugins and routes from the filesystem with
@fastify/autoload
Route Best Practicesroute-best-practices.mdMEDIUMOrganize routes with plugins/prefixes, use async handlers, full route options
Schema Validation (Zod)schema-validation-zod.mdHIGHType-safe validation with Zod +
fastify-type-provider-zod
Encapsulationencapsulation.mdHIGHProper scope isolation and when to use
fastify-plugin
Error Handlingerror-handling.mdHIGHCustom error handlers,
@fastify/error
, 404 handling, structured responses
Hooks & Lifecyclehooks-lifecycle.mdMEDIUMAll request/reply and application hooks: onRequest, preParsing, preValidation, preHandler, preSerialization, onError, onSend, onResponse, onTimeout, onRequestAbort, onReady, onListen, onClose, onRoute, onRegister
Logginglogging.mdHIGHBuilt-in Pino logger, request correlation, redaction, child loggers
Authenticationauthentication.mdHIGHJWT auth with
@fastify/jwt
, multi-strategy with
@fastify/auth
Testingtesting.mdHIGHTest with
inject()
, buildServer pattern, vitest/node:test
TypeScripttypescript-integration.mdMEDIUMType providers, module augmentation, typed decorators
Decoratorsdecorators.mdMEDIUMExtend the Fastify instance, request, and reply with
decorate
/
decorateRequest
/
decorateReply
Content Type Parsercontent-type-parser.mdHIGHCustom content type parsers, body limits, multipart uploads, catch-all and regex matching
规则按主题组织在
rules/
目录下。每条规则都遵循统一格式,包含影响级别、错误/正确示例以及官方文档参考链接。
规则名称文件路径影响级别描述
配置configuration.md环境配置、日志器设置、安全选项以及优雅关闭
创建服务器create-server.md低-中使用
buildServer()
工厂函数实现可复用、可测试的服务器搭建
创建插件create-plugin.md低-中使用
fastify-plugin
将可复用功能封装为插件
自动加载autoload.md使用
@fastify/autoload
自动从文件系统加载插件和路由
路由最佳实践route-best-practices.md使用插件/前缀组织路由、使用异步处理器、完整的路由选项
Schema验证(Zod)schema-validation-zod.md结合Zod与
fastify-type-provider-zod
实现类型安全的验证
封装encapsulation.md正确的作用域隔离以及
fastify-plugin
的使用场景
错误处理error-handling.md自定义错误处理器、
@fastify/error
、404处理、结构化响应
钩子与生命周期hooks-lifecycle.md所有请求/响应与应用钩子:onRequest、preParsing、preValidation、preHandler、preSerialization、onError、onSend、onResponse、onTimeout、onRequestAbort、onReady、onListen、onClose、onRoute、onRegister
日志logging.md内置Pino日志器、请求关联、内容脱敏、子日志器
身份验证authentication.md使用
@fastify/jwt
实现JWT认证、使用
@fastify/auth
实现多策略认证
测试testing.md使用
inject()
测试、buildServer模式、vitest/node:test
TypeScript集成typescript-integration.md类型提供器、模块扩展、类型化装饰器
装饰器decorators.md使用
decorate
/
decorateRequest
/
decorateReply
扩展Fastify实例、请求与响应对象
内容类型解析器content-type-parser.md自定义内容类型解析器、请求体大小限制、多部分上传、兜底与正则匹配

Usage

使用场景

When generating Fastify code, read the relevant rule file(s) for the topic and apply the patterns shown. For a new project, all rules are relevant. For specific tasks, load only what's needed:
  • New project setup:
    create-server.md
    ,
    configuration.md
    ,
    autoload.md
    ,
    encapsulation.md
    ,
    typescript-integration.md
  • Adding routes:
    route-best-practices.md
    ,
    autoload.md
    ,
    schema-validation-zod.md
  • Adding shared services:
    create-plugin.md
    ,
    autoload.md
    ,
    encapsulation.md
  • Configuration/environment:
    configuration.md
  • Error handling:
    error-handling.md
  • Auth/middleware:
    authentication.md
    ,
    hooks-lifecycle.md
    ,
    encapsulation.md
  • Custom decorators:
    decorators.md
    ,
    typescript-integration.md
  • Logging:
    logging.md
  • Body parsing/file uploads:
    content-type-parser.md
  • Writing tests:
    testing.md
    ,
    create-server.md
在生成Fastify代码时,阅读对应主题的规则文件并应用其中展示的模式。对于新项目,所有规则都适用;对于特定任务,仅加载所需规则即可:
  • 新项目搭建
    create-server.md
    configuration.md
    autoload.md
    encapsulation.md
    typescript-integration.md
  • 添加路由
    route-best-practices.md
    autoload.md
    schema-validation-zod.md
  • 添加共享服务
    create-plugin.md
    autoload.md
    encapsulation.md
  • 配置/环境
    configuration.md
  • 错误处理
    error-handling.md
  • 认证/中间件
    authentication.md
    hooks-lifecycle.md
    encapsulation.md
  • 自定义装饰器
    decorators.md
    typescript-integration.md
  • 日志
    logging.md
  • 请求体解析/文件上传
    content-type-parser.md
  • 编写测试
    testing.md
    create-server.md

Recommended Project Structure

推荐项目结构

Using
@fastify/autoload
, plugins and routes are loaded automatically from their directories:
src/
  plugins/          # Autoloaded — shared plugins (use fastify-plugin)
    db.ts
    auth.ts
    config.ts
  routes/           # Autoloaded — encapsulated route plugins (NO fastify-plugin)
    _hooks.ts       # Global route hooks (with autoHooks: true)
    users/
      index.ts      # → /users
      _hooks.ts     # Hooks for /users scope only
      schema.ts
    posts/
      index.ts      # → /posts
      schema.ts
  server.ts         # buildServer() with autoload registration
  app.ts            # Entry point — calls buildServer() and listen()
test/
  routes/
    users.test.ts
    posts.test.ts
  helpers.ts        # createTestServer() helper
借助
@fastify/autoload
,插件和路由会自动从对应目录加载:
src/
  plugins/          # 自动加载 — 共享插件(使用fastify-plugin)
    db.ts
    auth.ts
    config.ts
  routes/           # 自动加载 — 封装的路由插件(不使用fastify-plugin)
    _hooks.ts       # 全局路由钩子(开启autoHooks: true)
    users/
      index.ts      # → /users
      _hooks.ts     # 仅作用于/users范围的钩子
      schema.ts
    posts/
      index.ts      # → /posts
      schema.ts
  server.ts         # 注册了自动加载的buildServer()
  app.ts            # 入口文件 — 调用buildServer()并监听端口
test/
  routes/
    users.test.ts
    posts.test.ts
  helpers.ts        # createTestServer() 辅助函数

Present Results to User

向用户展示结果

When applying these best practices, mention which rule(s) you followed:
Applied Fastify best practices:
  • Route organization: Routes grouped by resource with prefixes
  • Zod validation: Request/response schemas with type inference
  • Encapsulation: Shared plugins use
    fastify-plugin
    , routes stay scoped
  • Error handling: Custom error handler with
    @fastify/error
在应用这些最佳实践时,说明遵循的规则:
已应用Fastify最佳实践:
  • 路由组织:按资源分组并使用前缀的路由
  • Zod验证:带类型推断的请求/响应Schema
  • 封装:共享插件使用
    fastify-plugin
    ,路由保持作用域隔离
  • 错误处理:基于
    @fastify/error
    的自定义错误处理器

Reference

参考链接