nestjs-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

NestJS 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

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1SecurityCRITICAL
security-
2PerformanceHIGH
performance-
3ArchitectureHIGH
architecture-
4Error HandlingHIGH
error-handling-
5ValidationCRITICAL
validation-
6DatabaseCRITICAL
database-
7AuthenticationCRITICAL
auth-
8APIMEDIUM
api-
9ConfigurationCRITICAL
config-
10TestingMEDIUM
testing-
11DeploymentMEDIUM
deployment-
12MiddlewareMEDIUM
middleware-
13AdvancedHIGH
advanced-
优先级类别影响程度前缀
1安全关键
security-
2性能
performance-
3架构
architecture-
4错误处理
error-handling-
5验证关键
validation-
6数据库关键
database-
7身份验证关键
auth-
8API
api-
9配置关键
config-
10测试
testing-
11部署
deployment-
12中间件
middleware-
13高级
advanced-

Quick Reference

快速参考

1. Security (CRITICAL)

1. 安全(关键)

  • security-cors-whitelist
    - Enable CORS with whitelist origins only
  • security-dependency-audit
    - Regular dependency security audits with bun
  • security-helmet-headers
    - Use Helmet middleware for security headers
  • security-cors-whitelist
    - 仅允许白名单源启用CORS
  • security-dependency-audit
    - 使用bun定期进行依赖项安全审计
  • security-helmet-headers
    - 使用Helmet中间件设置安全头

2. Performance (HIGH)

2. 性能(高)

  • performance-redis-caching
    - Cache frequently used data with Redis
  • performance-redis-caching
    - 使用Redis缓存频繁访问的数据

3. Architecture (HIGH)

3. 架构(高)

  • architecture-short-functions
    - Keep functions short and single purpose
  • architecture-feature-modules
    - Organize code by feature modules
  • architecture-no-dead-code
    - Remove unused code and dependencies
  • architecture-thin-controllers
    - Single responsibility - separate controller and service
  • architecture-naming-conventions
    - Use consistent naming conventions
  • architecture-event-driven
    - Use event-driven architecture for loose coupling
  • architecture-short-functions
    - 保持函数简短且单一职责
  • architecture-feature-modules
    - 按功能模块组织代码
  • architecture-no-dead-code
    - 移除未使用的代码与依赖项
  • architecture-thin-controllers
    - 单一职责 - 分离控制器与服务
  • architecture-naming-conventions
    - 使用一致的命名规范
  • architecture-event-driven
    - 使用事件驱动架构实现松耦合

4. Error Handling (HIGH)

4. 错误处理(高)

  • error-handling-exception-filter
    - Enable global exception filter
  • error-handling-structured-logging
    - Implement proper logging strategy
  • error-handling-exception-filter
    - 启用全局异常过滤器
  • error-handling-structured-logging
    - 实现合理的日志策略

5. Validation (CRITICAL)

5. 验证(关键)

  • validation-custom-pipes
    - Create custom pipes for query parameter transformation
  • validation-dto-validation
    - Validate all inputs with DTOs and ValidationPipe
  • validation-custom-pipes
    - 创建自定义管道用于查询参数转换
  • validation-dto-validation
    - 使用DTO与ValidationPipe验证所有输入

6. Database (CRITICAL)

6. 数据库(关键)

  • database-parameterized-queries
    - Use parameterized queries to prevent SQL injection (Prisma v7)
  • database-parameterized-queries
    - 使用参数化查询防止SQL注入(Prisma v7)

7. Authentication (CRITICAL)

7. 身份验证(关键)

  • auth-password-hashing
    - Use Bun's built-in Crypto for secure password hashing (argon2/bcrypt)
  • auth-route-guards
    - Use guards for route protection
  • auth-password-hashing
    - 使用Bun内置的Crypto进行安全密码哈希(argon2/bcrypt)
  • auth-route-guards
    - 使用守卫保护路由

8. API (MEDIUM)

8. API(中)

  • api-cursor-pagination
    - Use cursor-based pagination for large datasets
  • api-swagger-docs
    - Generate Swagger/OpenAPI documentation
  • api-cursor-pagination
    - 对大型数据集使用基于游标分页
  • api-swagger-docs
    - 生成Swagger/OpenAPI文档

9. Configuration (CRITICAL)

9. 配置(关键)

  • config-no-secrets
    - Never hardcode secrets - use environment variables
  • config-no-secrets
    - 切勿硬编码密钥 - 使用环境变量

10. Testing (MEDIUM)

10. 测试(中)

  • testing-unit-tests
    - Write comprehensive unit tests
  • testing-unit-tests
    - 编写全面的单元测试

11. Deployment (MEDIUM)

11. 部署(中)

  • deployment-health-checks
    - Implement health check endpoints
  • deployment-health-checks
    - 实现健康检查端点

12. Middleware (MEDIUM)

12. 中间件(中)

  • middleware-compression
    - Enable compression middleware for responses
  • middleware-rate-limiting
    - Implement rate limiting for all routes
  • middleware-compression
    - 启用响应压缩中间件
  • middleware-rate-limiting
    - 为所有路由实现速率限制

13. Advanced (HIGH)

13. 高级(高)

  • advanced-lazy-loading
    - Lazy load non-critical modules
  • advanced-scheduled-tasks
    - Use @nestjs/schedule for cron jobs and scheduled tasks
  • advanced-lazy-loading
    - 懒加载非关键模块
  • advanced-scheduled-tasks
    - 使用@nestjs/schedule实现定时任务与计划任务

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.md
Each 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.md

Build 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 validate
bash
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优化,适用于自动化代码生成与评审