fastify-best-practise
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseFastify 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
工作原理
- The agent identifies that the user is working with Fastify or asking about Fastify patterns
- The relevant rule file is loaded based on the topic (routes, validation, encapsulation, etc.)
- The agent applies the best practices from the rule when generating or reviewing code
- Agent识别到用户正在使用Fastify或询问Fastify相关模式
- 根据主题(路由、验证、封装等)加载对应的规则文件
- Agent在生成或评审代码时,应用规则中的最佳实践
Rules
规则
The rules are organized by topic in the directory. Each rule follows a consistent format with impact rating, incorrect/correct examples, and references to official docs.
rules/| Rule | File | Impact | Description |
|---|---|---|---|
| Configuration | configuration.md | HIGH | Environment config, logger setup, security options, and graceful shutdown |
| Create Server | create-server.md | LOW-MEDIUM | Use a |
| Create Plugin | create-plugin.md | LOW-MEDIUM | Encapsulate reusable functionality in plugins with |
| Autoload | autoload.md | HIGH | Automatically load plugins and routes from the filesystem with |
| Route Best Practices | route-best-practices.md | MEDIUM | Organize routes with plugins/prefixes, use async handlers, full route options |
| Schema Validation (Zod) | schema-validation-zod.md | HIGH | Type-safe validation with Zod + |
| Encapsulation | encapsulation.md | HIGH | Proper scope isolation and when to use |
| Error Handling | error-handling.md | HIGH | Custom error handlers, |
| Hooks & Lifecycle | hooks-lifecycle.md | MEDIUM | All request/reply and application hooks: onRequest, preParsing, preValidation, preHandler, preSerialization, onError, onSend, onResponse, onTimeout, onRequestAbort, onReady, onListen, onClose, onRoute, onRegister |
| Logging | logging.md | HIGH | Built-in Pino logger, request correlation, redaction, child loggers |
| Authentication | authentication.md | HIGH | JWT auth with |
| Testing | testing.md | HIGH | Test with |
| TypeScript | typescript-integration.md | MEDIUM | Type providers, module augmentation, typed decorators |
| Decorators | decorators.md | MEDIUM | Extend the Fastify instance, request, and reply with |
| Content Type Parser | content-type-parser.md | HIGH | Custom content type parsers, body limits, multipart uploads, catch-all and regex matching |
规则按主题组织在目录下。每条规则都遵循统一格式,包含影响级别、错误/正确示例以及官方文档参考链接。
rules/| 规则名称 | 文件路径 | 影响级别 | 描述 |
|---|---|---|---|
| 配置 | configuration.md | 高 | 环境配置、日志器设置、安全选项以及优雅关闭 |
| 创建服务器 | create-server.md | 低-中 | 使用 |
| 创建插件 | create-plugin.md | 低-中 | 使用 |
| 自动加载 | autoload.md | 高 | 使用 |
| 路由最佳实践 | route-best-practices.md | 中 | 使用插件/前缀组织路由、使用异步处理器、完整的路由选项 |
| Schema验证(Zod) | schema-validation-zod.md | 高 | 结合Zod与 |
| 封装 | encapsulation.md | 高 | 正确的作用域隔离以及 |
| 错误处理 | error-handling.md | 高 | 自定义错误处理器、 |
| 钩子与生命周期 | hooks-lifecycle.md | 中 | 所有请求/响应与应用钩子:onRequest、preParsing、preValidation、preHandler、preSerialization、onError、onSend、onResponse、onTimeout、onRequestAbort、onReady、onListen、onClose、onRoute、onRegister |
| 日志 | logging.md | 高 | 内置Pino日志器、请求关联、内容脱敏、子日志器 |
| 身份验证 | authentication.md | 高 | 使用 |
| 测试 | testing.md | 高 | 使用 |
| TypeScript集成 | typescript-integration.md | 中 | 类型提供器、模块扩展、类型化装饰器 |
| 装饰器 | decorators.md | 中 | 使用 |
| 内容类型解析器 | 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.mdtypescript-integration.md - Adding routes: ,
route-best-practices.md,autoload.mdschema-validation-zod.md - Adding shared services: ,
create-plugin.md,autoload.mdencapsulation.md - Configuration/environment:
configuration.md - Error handling:
error-handling.md - Auth/middleware: ,
authentication.md,hooks-lifecycle.mdencapsulation.md - Custom decorators: ,
decorators.mdtypescript-integration.md - Logging:
logging.md - Body parsing/file uploads:
content-type-parser.md - Writing tests: ,
testing.mdcreate-server.md
在生成Fastify代码时,阅读对应主题的规则文件并应用其中展示的模式。对于新项目,所有规则都适用;对于特定任务,仅加载所需规则即可:
- 新项目搭建:、
create-server.md、configuration.md、autoload.md、encapsulation.mdtypescript-integration.md - 添加路由:、
route-best-practices.md、autoload.mdschema-validation-zod.md - 添加共享服务:、
create-plugin.md、autoload.mdencapsulation.md - 配置/环境:
configuration.md - 错误处理:
error-handling.md - 认证/中间件:、
authentication.md、hooks-lifecycle.mdencapsulation.md - 自定义装饰器:、
decorators.mdtypescript-integration.md - 日志:
logging.md - 请求体解析/文件上传:
content-type-parser.md - 编写测试:、
testing.mdcreate-server.md
Recommended Project Structure
推荐项目结构
Using , plugins and routes are loaded automatically from their directories:
@fastify/autoloadsrc/
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/autoloadsrc/
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
, routes stay scopedfastify-plugin- Error handling: Custom error handler with
@fastify/error
在应用这些最佳实践时,说明遵循的规则:
已应用Fastify最佳实践:
- 路由组织:按资源分组并使用前缀的路由
- Zod验证:带类型推断的请求/响应Schema
- 封装:共享插件使用
,路由保持作用域隔离fastify-plugin- 错误处理:基于
的自定义错误处理器@fastify/error