nestjs-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNestJS Best Practices
NestJS 最佳实践
Comprehensive guide for building production-ready NestJS applications. Contains 26 rules across 13 categories, covering security, architecture, performance, validation, database operations, authentication, and advanced patterns.
构建生产级NestJS应用的综合指南。涵盖13个类别共26条规则,涉及安全、架构、性能、验证、数据库操作、身份验证及高级模式。
When to Apply
适用场景
Reference these guidelines when:
- Writing new NestJS modules, controllers, or services
- Implementing authentication and authorization
- Setting up Prisma database operations
- Creating DTOs and validation pipes
- Adding middleware or guards
- Implementing error handling and logging
- Reviewing NestJS code for best practices
- Refactoring existing NestJS applications
在以下场景中参考本指南:
- 编写新的NestJS模块、控制器或服务
- 实现身份验证与授权
- 配置Prisma数据库操作
- 创建DTO与验证管道
- 添加中间件或守卫
- 实现错误处理与日志记录
- 评审NestJS代码以遵循最佳实践
- 重构现有NestJS应用
Rule Categories by Priority
按优先级划分的规则类别
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Security | CRITICAL | |
| 2 | Performance | HIGH | |
| 3 | Architecture | HIGH | |
| 4 | Error Handling | HIGH | |
| 5 | Validation | CRITICAL | |
| 6 | Database | CRITICAL | |
| 7 | Authentication | CRITICAL | |
| 8 | API | MEDIUM | |
| 9 | Configuration | CRITICAL | |
| 10 | Testing | MEDIUM | |
| 11 | Deployment | MEDIUM | |
| 12 | Middleware | MEDIUM | |
| 13 | Advanced | HIGH | |
| 优先级 | 类别 | 影响程度 | 前缀 |
|---|---|---|---|
| 1 | 安全 | 关键 | |
| 2 | 性能 | 高 | |
| 3 | 架构 | 高 | |
| 4 | 错误处理 | 高 | |
| 5 | 验证 | 关键 | |
| 6 | 数据库 | 关键 | |
| 7 | 身份验证 | 关键 | |
| 8 | API | 中 | |
| 9 | 配置 | 关键 | |
| 10 | 测试 | 中 | |
| 11 | 部署 | 中 | |
| 12 | 中间件 | 中 | |
| 13 | 高级 | 高 | |
Quick Reference
快速参考
1. Security (CRITICAL)
1. 安全(关键)
- - Enable CORS with whitelist origins only
security-cors-whitelist - - Regular dependency security audits with bun
security-dependency-audit - - Use Helmet middleware for security headers
security-helmet-headers
- - 仅允许白名单源启用CORS
security-cors-whitelist - - 使用bun定期进行依赖项安全审计
security-dependency-audit - - 使用Helmet中间件设置安全头
security-helmet-headers
2. Performance (HIGH)
2. 性能(高)
- - Cache frequently used data with Redis
performance-redis-caching
- - 使用Redis缓存频繁访问的数据
performance-redis-caching
3. Architecture (HIGH)
3. 架构(高)
- - Keep functions short and single purpose
architecture-short-functions - - Organize code by feature modules
architecture-feature-modules - - Remove unused code and dependencies
architecture-no-dead-code - - Single responsibility - separate controller and service
architecture-thin-controllers - - Use consistent naming conventions
architecture-naming-conventions - - Use event-driven architecture for loose coupling
architecture-event-driven
- - 保持函数简短且单一职责
architecture-short-functions - - 按功能模块组织代码
architecture-feature-modules - - 移除未使用的代码与依赖项
architecture-no-dead-code - - 单一职责 - 分离控制器与服务
architecture-thin-controllers - - 使用一致的命名规范
architecture-naming-conventions - - 使用事件驱动架构实现松耦合
architecture-event-driven
4. Error Handling (HIGH)
4. 错误处理(高)
- - Enable global exception filter
error-handling-exception-filter - - Implement proper logging strategy
error-handling-structured-logging
- - 启用全局异常过滤器
error-handling-exception-filter - - 实现合理的日志策略
error-handling-structured-logging
5. Validation (CRITICAL)
5. 验证(关键)
- - Create custom pipes for query parameter transformation
validation-custom-pipes - - Validate all inputs with DTOs and ValidationPipe
validation-dto-validation
- - 创建自定义管道用于查询参数转换
validation-custom-pipes - - 使用DTO与ValidationPipe验证所有输入
validation-dto-validation
6. Database (CRITICAL)
6. 数据库(关键)
- - Use parameterized queries to prevent SQL injection (Prisma v7)
database-parameterized-queries
- - 使用参数化查询防止SQL注入(Prisma v7)
database-parameterized-queries
7. Authentication (CRITICAL)
7. 身份验证(关键)
- - Use Bun's built-in Crypto for secure password hashing (argon2/bcrypt)
auth-password-hashing - - Use guards for route protection
auth-route-guards
- - 使用Bun内置的Crypto进行安全密码哈希(argon2/bcrypt)
auth-password-hashing - - 使用守卫保护路由
auth-route-guards
8. API (MEDIUM)
8. API(中)
- - Use cursor-based pagination for large datasets
api-cursor-pagination - - Generate Swagger/OpenAPI documentation
api-swagger-docs
- - 对大型数据集使用基于游标分页
api-cursor-pagination - - 生成Swagger/OpenAPI文档
api-swagger-docs
9. Configuration (CRITICAL)
9. 配置(关键)
- - Never hardcode secrets - use environment variables
config-no-secrets
- - 切勿硬编码密钥 - 使用环境变量
config-no-secrets
10. Testing (MEDIUM)
10. 测试(中)
- - Write comprehensive unit tests
testing-unit-tests
- - 编写全面的单元测试
testing-unit-tests
11. Deployment (MEDIUM)
11. 部署(中)
- - Implement health check endpoints
deployment-health-checks
- - 实现健康检查端点
deployment-health-checks
12. Middleware (MEDIUM)
12. 中间件(中)
- - Enable compression middleware for responses
middleware-compression - - Implement rate limiting for all routes
middleware-rate-limiting
- - 启用响应压缩中间件
middleware-compression - - 为所有路由实现速率限制
middleware-rate-limiting
13. Advanced (HIGH)
13. 高级(高)
- - Lazy load non-critical modules
advanced-lazy-loading - - Use @nestjs/schedule for cron jobs and scheduled tasks
advanced-scheduled-tasks
- - 懒加载非关键模块
advanced-lazy-loading - - 使用@nestjs/schedule实现定时任务与计划任务
advanced-scheduled-tasks
How to Use
使用方法
Read individual rule files for detailed explanations and code examples:
rules/security-cors-whitelist.md
rules/auth-route-guards.md
rules/validation-dto-validation.md
rules/_sections.mdEach rule file contains:
- "For AI Agents" section with step-by-step implementation instructions
- Quick Reference Checklist for code review
- ❌ WRONG vs ✅ CORRECT patterns with file locations
- Installation commands using
bun add - Comprehensive code examples for NestJS + Prisma
- Security and performance considerations
阅读单个规则文件获取详细说明与代码示例:
rules/security-cors-whitelist.md
rules/auth-route-guards.md
rules/validation-dto-validation.md
rules/_sections.md每个规则文件包含:
- 面向AI Agent的分步实现说明章节
- 代码评审快速参考清单
- ❌ 错误 vs ✅ 正确的模式对比及文件位置
- 使用的安装命令
bun add - NestJS + Prisma的综合代码示例
- 安全与性能考量
Key Patterns
核心模式
Agent-Friendly Format
适配Agent的格式
All rules are optimized for AI agents with:
- Explicit file locations (e.g., )
src/users/users.service.ts - Step-by-step "For AI Agents" sections
- ✅ CORRECT vs ❌ WRONG pattern comparisons
- Quick Reference Checklists
- Clear installation instructions
所有规则均针对AI Agent优化,包含:
- 明确的文件位置(例如)
src/users/users.service.ts - 分步的“面向AI Agent”章节
- ✅ 正确 vs ❌ 错误的模式对比
- 快速参考清单
- 清晰的安装说明
Technology Stack
技术栈
- Framework: NestJS with Express/Fastify adapter
- Runtime: Bun (native crypto, scheduling)
- Database: Prisma v7 (sql template tag, interactive transactions)
- Validation: class-validator + class-transformer
- Security: Helmet, CORS whitelisting, rate limiting
- Scheduling: @nestjs/schedule with cron/interval decorators
- Events: EventEmitter2 for loose coupling
- 框架:NestJS(搭配Express/Fastify适配器)
- 运行时:Bun(原生加密、调度功能)
- 数据库:Prisma v7(SQL模板标签、交互式事务)
- 验证:class-validator + class-transformer
- 安全:Helmet、CORS白名单、速率限制
- 调度:使用@nestjs/schedule实现 cron 任务与计划任务
- 事件:EventEmitter2实现松耦合
Full Compiled Document
完整编译文档
For the complete guide with all rules expanded:
AGENTS.md包含所有规则详细内容的完整指南:
AGENTS.mdBuild Commands
构建命令
bash
cd packages/nestjs-best-practices-build
bun install
bun run build # Generate AGENTS.md
bun run validate # Validate rule files
bun run dev # Build and validatebash
cd packages/nestjs-best-practices-build
bun install
bun run build # 生成AGENTS.md
bun run validate # 验证规则文件
bun run dev # 构建并验证Statistics
统计信息
- 13 sections covering all aspects of NestJS development
- 26 rules prioritized by impact (CRITICAL, HIGH, MEDIUM)
- Prisma v7 compatible database patterns
- Bun runtime native features (Crypto.hashPassword, @nestjs/schedule)
- Agent-optimized for automated code generation and review
- 13个章节,覆盖NestJS开发的所有方面
- 26条规则,按影响程度优先级划分(关键、高、中)
- 兼容Prisma v7的数据库模式
- 利用Bun运行时的原生功能(Crypto.hashPassword、@nestjs/schedule)
- 针对Agent优化,适用于自动化代码生成与评审