Hướng dẫn toàn diện từ khởi tạo đến triển khai dự án Node.js/TypeScript, theo đúng quy trình phát triển phần mềm chuyên nghiệp.
Mở terminal, tạo thư mục và khởi chạy Claude Code:
mkdir my-project && cd my-project
claude
Sau khi Claude Code khởi động, gửi prompt khởi tạo:
Tạo dự án Node.js TypeScript với:
- package.json với scripts chuẩn (dev, build, start, test, lint)
- tsconfig.json cho Node.js 20+ (ES2022, NodeNext module)
- ESLint flat config + Prettier
- .gitignore cho Node.js
- Dockerfile + docker-compose.yml
- .env.example với các biến môi trường mẫu
- nodemon.json cho development
Tạo dự án Express TypeScript REST API theo template chuẩn enterprise:
- Express + TypeScript strict mode
- Cấu trúc thư mục theo Clean Architecture
- Tích hợp sẵn health check endpoint
- Docker multi-stage build
- Husky + lint-staged cho pre-commit hooks
- GitHub Actions CI/CD pipeline cơ bản
my-project/
├── src/
│ ├── config/ # Cấu hình app (database, redis, env)
│ ├── controllers/ # Route handlers - xử lý request/response
│ ├── middlewares/ # Express middlewares (auth, logging, error)
│ ├── models/ # Database models / Prisma schema
│ ├── routes/ # Route definitions
│ ├── services/ # Business logic chính
│ ├── repositories/ # Data access layer
│ ├── utils/ # Utility functions (helpers, formatters)
│ ├── validators/ # Input validation schemas (Zod)
│ ├── types/ # TypeScript types & interfaces
│ ├── constants/ # Hằng số, enum
│ └── index.ts # Entry point
├── tests/
│ ├── unit/ # Unit tests
│ ├── integration/ # Integration tests
│ └── e2e/ # End-to-end tests
├── prisma/
│ ├── schema.prisma # Database schema
│ ├── migrations/ # Database migrations
│ └── seed.ts # Seed data
├── docker/
│ └── Dockerfile # Production Dockerfile
├── .github/
│ └── workflows/ # CI/CD pipelines
├── tsconfig.json
├── package.json
├── docker-compose.yml
├── .env.example
├── .eslintrc.js
├── .prettierrc
└── README.md
Tạo tsconfig.json cho Node.js 20+ với:
- target: ES2022
- module: NodeNext
- moduleResolution: NodeNext
- strict: true (bật tất cả strict checks)
- Path aliases: @config, @controllers, @services, @models, @utils, @types
- outDir: dist
- rootDir: src
- declaration: true cho type exports
Cập nhật package.json với các scripts sau:
- dev: chạy development server với hot reload (tsx watch hoặc nodemon)
- build: compile TypeScript sang JavaScript
- start: chạy production build
- test: chạy toàn bộ test suite
- test:watch: chạy test ở chế độ watch
- test:coverage: chạy test với coverage report
- lint: kiểm tra lỗi ESLint
- lint:fix: tự động sửa lỗi ESLint
- format: format code với Prettier
- db:migrate: chạy database migrations
- db:seed: chạy seed data
- db:studio: mở Prisma Studio
- docker:dev: chạy docker-compose cho development
- docker:prod: build và chạy production container
/engineering-skills:senior-architect
Thiết kế lại dự án theo Clean Architecture với 4 layers:
1. Domain Layer (entities, value objects, domain services) - không phụ thuộc gì
2. Application Layer (use cases, DTOs, ports/interfaces) - chỉ phụ thuộc Domain
3. Infrastructure Layer (database, external APIs, implementations) - implement interfaces
4. Presentation Layer (controllers, routes, middleware) - gọi Application Layer
Đảm bảo:
- Dependency Inversion: các layer trong không biết layer ngoài
- Dùng interfaces để tách biệt các layer
- Tạo ví dụ cụ thể với module User (tạo user, lấy danh sách, cập nhật)
Áp dụng Domain-Driven Design cho module E-commerce:
- Bounded Contexts: User, Product, Order, Payment
- Aggregate Roots cho mỗi context
- Value Objects (Money, Email, Address)
- Domain Events (OrderCreated, PaymentCompleted)
- Repository interfaces ở Domain layer
- Tạo cấu trúc thư mục phản ánh các bounded contexts
Thiết kế hệ thống microservices cho ứng dụng e-commerce:
- API Gateway (Express + rate limiting)
- Service Discovery pattern
- Circuit Breaker pattern (dùng opossum)
- Event-driven communication (RabbitMQ hoặc Redis Pub/Sub)
- Shared types package
- Monorepo với Turborepo
- Docker Compose cho local development
Vẽ sơ đồ kiến trúc bằng ASCII art.
Chuyển đổi module Payment sang Hexagonal Architecture:
- Ports: interfaces cho các tương tác bên ngoài
+ Driving ports: PaymentController interface
+ Driven ports: PaymentGateway interface, PaymentRepository interface
- Adapters:
+ Driving adapters: Express route handler
+ Driven adapters: StripeGateway, PostgresPaymentRepository
- Core domain logic hoàn toàn independent
Tạo REST API với Express và TypeScript:
1. Setup Express app với middleware chuẩn:
- cors, helmet, compression, morgan
- JSON body parser với size limit
- Error handling middleware
2. Tạo endpoints:
- POST /api/auth/register - đăng ký user mới
- POST /api/auth/login - đăng nhập, trả về JWT
- POST /api/auth/refresh - refresh token
- GET /api/users - lấy danh sách users (protected, admin only)
- GET /api/users/:id - lấy thông tin user (protected)
- PUT /api/users/:id - cập nhật user (protected, owner only)
- DELETE /api/users/:id - xóa user (protected, admin only)
3. Sử dụng:
- TypeScript strict mode
- Zod validation cho tất cả input
- Response typing nhất quán (ApiResponse<T>)
- HTTP status codes chuẩn
Tạo CRUD đầy đủ cho resource Product:
- Model: id, name, description, price, category, imageUrl, stock, createdAt, updatedAt
- Endpoints: GET (list + pagination + filter), GET/:id, POST, PUT/:id, PATCH/:id, DELETE/:id
- Validation: Zod schemas cho create, update, query params
- Service layer với business logic
- Repository layer với Prisma
- Route + Controller + Service + Repository + Validator + Types
- Tự động đăng ký route trong router chính
Tạo cấu trúc API response chuẩn và áp dụng cho toàn bộ project:
// Thành công
{
"success": true,
"data": T,
"meta": { "page": 1, "limit": 20, "total": 100 } // cho list
}
// Lỗi
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Dữ liệu không hợp lệ",
"details": [{ "field": "email", "message": "Email không đúng định dạng" }]
}
}
Tạo utility functions: successResponse(), errorResponse(), paginatedResponse().
Tạo TypeScript generics cho type safety.
Tạo module pagination/filtering/sorting tái sử dụng:
- Query params: ?page=1&limit=20&sort=createdAt&order=desc&search=keyword
- Filter theo từng field: ?status=active&category=electronics&minPrice=100&maxPrice=500
- Cursor-based pagination option cho large datasets
- Zod schema validate query params
- Prisma query builder từ parsed params
- Response metadata: page, limit, total, totalPages, hasNext, hasPrev
Tạo module upload file:
- POST /api/upload/single - upload 1 file
- POST /api/upload/multiple - upload nhiều file
- Sử dụng Multer middleware
- Validation: file size, file type (chỉ cho phép image, pdf)
- Lưu trữ: local storage (development) và S3 (production)
- Tạo thumbnail cho image uploads
- Trả về URL file đã upload
- Xóa file khi record bị xóa
Thêm WebSocket vào Express app hiện tại:
- Sử dụng Socket.IO
- Namespace cho từng feature: /chat, /notifications
- Authentication middleware cho WebSocket connections
- Room-based messaging
- Events: connection, disconnect, sendMessage, typing, joinRoom, leaveRoom
- Broadcast notifications cho online users
- TypeScript types cho tất cả events
Cài đặt và cấu hình Prisma ORM với PostgreSQL:
1. Schema cho các models:
- User: id, email (unique), password, name, role (USER/ADMIN), avatar, isActive, createdAt, updatedAt
- Profile: id, userId (1-1), bio, phone, address, dateOfBirth
- Post: id, title, content, slug (unique), status (DRAFT/PUBLISHED), authorId (n-1), categoryId, createdAt, updatedAt
- Category: id, name, slug (unique), parentId (self-relation cho nested categories)
- Comment: id, content, postId (n-1), authorId (n-1), parentId (self-relation cho nested comments), createdAt
- Tag: id, name, slug (unique)
- PostTag: postId, tagId (many-to-many join table)
2. Relations đầy đủ với cascade delete/update
3. Indexes cho các trường hay query
4. Migration đầu tiên
5. Seed data với faker.js (10 users, 50 posts, 20 categories, 200 comments)
Tạo repository layer cho Post model với các query nâng cao:
- findAll: pagination, filtering (status, category, author, date range), sorting, search full-text
- findBySlug: include author, category, tags, comment count
- findRelated: posts cùng category hoặc tags, exclude current post
- getStats: tổng posts theo status, theo category, theo tháng (group by)
- Sử dụng Prisma transactions cho các operations phức tạp
- Soft delete pattern (deletedAt field thay vì xóa thật)
- Optimistic locking với version field
Hướng dẫn quy trình migration chuẩn:
1. Thêm field "viewCount" (Int, default 0) và "publishedAt" (DateTime, nullable) vào Post model
2. Tạo migration
3. Viết data migration script: set publishedAt = createdAt cho các posts đã PUBLISHED
4. Tạo index cho publishedAt
5. Rollback strategy nếu cần
Tạo database layer với MongoDB và Mongoose:
- Connection manager với retry logic
- Schema definitions với TypeScript interfaces
- Virtual fields và methods
- Pre/post hooks cho validation và data transformation
- Aggregation pipeline examples
- Text search index
- Population strategy (khi nào dùng reference vs embed)
Tích hợp Redis vào project:
- Connection manager với ioredis
- Utility functions: get, set, del, setWithExpiry, getOrSet (cache-aside pattern)
- Session storage
- Rate limiting data
- Pub/Sub cho realtime features
- Redis Streams cho message queue đơn giản
- Health check cho Redis connection
Implement hệ thống JWT authentication hoàn chỉnh:
1. Token Strategy:
- Access token: JWT, expire 15 phút, chứa userId + role
- Refresh token: random string, expire 7 ngày, lưu trong database
- Token rotation: mỗi lần refresh thì cả access và refresh token đều mới
2. Endpoints:
- POST /api/auth/register: validate input, hash password, tạo user, gửi verification email
- POST /api/auth/login: verify credentials, trả về access + refresh token
- POST /api/auth/refresh: validate refresh token, rotate tokens
- POST /api/auth/logout: revoke refresh token
- POST /api/auth/forgot-password: gửi email reset link
- POST /api/auth/reset-password: đặt lại mật khẩu
- GET /api/auth/verify-email/:token: xác thực email
3. Security:
- bcrypt hash password với salt rounds = 12
- Rate limiting: 5 login attempts / 15 phút
- Refresh token family detection (phát hiện token bị đánh cắp)
- Blacklist tokens khi logout
Implement RBAC system:
1. Roles: SUPER_ADMIN, ADMIN, MODERATOR, USER, GUEST
2. Permissions:
- users:read, users:create, users:update, users:delete
- posts:read, posts:create, posts:update, posts:delete, posts:publish
- comments:read, comments:create, comments:update, comments:delete
- admin:dashboard, admin:settings
3. Middleware:
- authenticate: verify JWT, attach user to request
- authorize(...roles): kiểm tra role
- checkPermission(...permissions): kiểm tra permission cụ thể
- checkOwnership(resourceField): chỉ cho phép owner hoặc admin
4. Database: Role model + Permission model + RolePermission (many-to-many)
5. Caching: cache role-permissions trong Redis
Thêm Social Login vào hệ thống auth hiện tại:
- Google OAuth2 với Passport.js
- GitHub OAuth2
- Callback handler: tạo user mới hoặc link với account hiện tại
- Merge accounts: cho phép user link nhiều social accounts
- TypeScript types cho OAuth profiles
- Environment variables cho client ID/secret
Implement API Key authentication cho external integrations:
- Generate API key (prefix + random bytes + checksum)
- Hash API key trong database (không lưu plaintext)
- Rate limiting per API key
- Scope/permission per API key
- API key rotation (tạo key mới, grace period cho key cũ)
- Middleware xác thực API key từ header X-API-Key
Cấu hình môi trường testing hoàn chỉnh:
- Jest với ts-jest cho TypeScript
- jest.config.ts với path aliases
- Test database riêng (SQLite hoặc PostgreSQL test container)
- Global setup/teardown: migrate + seed trước khi test, cleanup sau
- Test utilities: createTestUser(), authenticatedRequest(), mockRedis()
- Custom matchers cho API responses
- Coverage threshold: statements 80%, branches 75%, functions 80%, lines 80%
Viết unit tests cho UserService:
- register: test happy path, test duplicate email, test weak password
- login: test thành công, test sai password, test user không tồn tại, test user bị khóa
- updateProfile: test cập nhật thành công, test validation errors
- changePassword: test đổi mật khẩu thành công, test mật khẩu cũ sai
Sử dụng:
- jest.mock() cho repository và external services
- describe/it blocks có cấu trúc rõ ràng
- Arrange-Act-Assert pattern
- Tên test bằng tiếng Việt mô tả rõ behavior
Viết integration tests cho Auth module:
- Test full flow: register → verify email → login → access protected route → refresh token → logout
- Test với database thật (test container)
- Test middleware chain hoạt động đúng
- Test error responses đúng format
- Test rate limiting hoạt động
- Reset database state giữa các test
- Sử dụng Supertest cho HTTP requests
Viết API tests cho Product CRUD:
- GET /api/products: test pagination, filtering, sorting, search
- GET /api/products/:id: test found, not found, invalid id format
- POST /api/products: test tạo thành công, test validation errors, test unauthorized
- PUT /api/products/:id: test update thành công, test partial update, test not found
- DELETE /api/products/:id: test xóa thành công, test not found, test forbidden (không phải owner)
Mỗi test case gồm: mô tả tiếng Việt, request setup, response assertion (status, body, headers).
/engineering-skills:tdd-guide
Áp dụng TDD để xây dựng module CartService:
1. Red: Viết test trước - addItem, removeItem, updateQuantity, getTotal, applyCoupon, checkout
2. Green: Implement code tối thiểu để pass test
3. Refactor: Tối ưu code mà không break tests
Bắt đầu từ test đơn giản nhất (addItem) rồi tăng dần complexity.
/engineering-skills:senior-qa
Review bộ test hiện tại và đề xuất cải thiện:
- Tìm test cases còn thiếu (edge cases, error cases)
- Kiểm tra test isolation (tests có phụ thuộc nhau không?)
- Đánh giá test coverage và đề xuất bổ sung
- Kiểm tra test performance (có test nào chạy quá lâu?)
- Đề xuất test data management strategy
Implement hệ thống error handling tập trung:
1. Custom Error Classes (kế thừa từ base AppError):
- ValidationError (400): lỗi validation input
- AuthenticationError (401): chưa đăng nhập
- ForbiddenError (403): không có quyền
- NotFoundError (404): resource không tìm thấy
- ConflictError (409): duplicate resource
- RateLimitError (429): quá nhiều requests
- InternalError (500): lỗi server
2. Mỗi error class có:
- HTTP status code
- Error code string (dùng cho frontend mapping)
- Message mặc định
- Optional details (validation errors array)
- Stack trace (chỉ hiển thị trong development)
3. Error Middleware:
- Catch tất cả errors
- Log error (khác nhau cho từng severity)
- Format response theo chuẩn đã định
- Handle Prisma errors (unique constraint, not found, etc.)
- Handle Zod validation errors
- Handle JWT errors (expired, invalid, malformed)
- Không leak internal details trong production
Tạo utility wrapper cho async route handlers:
- asyncHandler: wrap async function, tự động catch errors và forward tới error middleware
- Không cần try-catch trong mỗi controller
- TypeScript overloads cho Request generic types
- Áp dụng cho tất cả routes hiện có
Implement logging system với Winston:
1. Logger Config:
- Console transport: colorized, human-readable (development)
- File transport: JSON format, rotation hàng ngày (production)
- Separate files: error.log (errors only), combined.log (all), access.log (HTTP requests)
- Log levels: error, warn, info, http, debug
2. Request Logger Middleware:
- Log mỗi request: method, url, status, response time, IP, user agent
- Request ID tracking (UUID, truyền qua headers)
- Correlation ID cho distributed tracing
3. Contextual Logging:
- Tạo child logger với context (userId, requestId)
- Structured logging format cho log aggregation
- Sensitive data masking (password, token, credit card)
4. Integration:
- Morgan → Winston cho HTTP logs
- Prisma query logging ở debug level
- Unhandled rejection & uncaught exception handling
Tạo health check endpoint chi tiết:
- GET /health: status tổng quát (UP/DOWN)
- GET /health/detail: kiểm tra từng dependency
+ Database: connection + query latency
+ Redis: connection + ping latency
+ External APIs: response check
+ Disk space: usage percentage
+ Memory: heap usage
- Response time cho mỗi check
- Graceful degradation: partial healthy nếu non-critical service down
Implement caching strategy với Redis:
1. Cache-Aside Pattern:
- Decorator/wrapper cho service methods
- Tự động cache result với TTL
- Cache invalidation khi data thay đổi
- Cache key naming convention: module:entity:id:action
2. Cache cho:
- GET /api/products (list): cache 5 phút, invalidate khi CRUD
- GET /api/products/:id: cache 10 phút, invalidate khi update/delete
- User permissions: cache 30 phút, invalidate khi role thay đổi
- API rate limiting counters
3. Cache utilities:
- cacheGet<T>(key): get và parse JSON
- cacheSet(key, value, ttl): stringify và set
- cacheDelete(pattern): xóa theo pattern
- cacheClearModule(module): xóa toàn bộ cache của 1 module
4. Cache warming: preload popular data khi server start
Tối ưu database queries trong project:
- Phân tích slow queries bằng Prisma logging
- Thêm indexes cho các trường hay filter/sort
- Optimize N+1 queries (dùng include/select đúng cách)
- Implement pagination bằng cursor thay vì offset cho large tables
- Sử dụng Prisma.$queryRaw cho complex aggregations
- Connection pooling configuration
- Read replicas cho heavy read operations
- Batch operations: createMany, updateMany thay vì loop
Tối ưu response performance:
- Compression middleware (gzip/brotli)
- ETags cho cache validation
- Conditional requests (If-None-Match, If-Modified-Since)
- Response field selection: ?fields=id,name,email (sparse fieldsets)
- Payload size optimization: không trả về fields không cần thiết
- Streaming response cho large datasets
Cấu hình connection pooling:
- Prisma connection pool: min 2, max 10, timeout 5s
- Redis connection pool với ioredis cluster mode
- HTTP keep-alive cho external API calls (axios/undici)
- Graceful shutdown: đóng tất cả connections khi server stop
- Health monitoring cho connection pools
- Auto-reconnect strategy
Tạo hệ thống background jobs:
- Sử dụng BullMQ với Redis
- Queue definitions: emailQueue, notificationQueue, reportQueue
- Job processors với retry logic
- Delayed jobs (gửi email reminder sau 24h)
- Recurring jobs (cleanup expired tokens mỗi ngày)
- Job dashboard (Bull Board)
- Dead letter queue cho failed jobs
- Graceful shutdown: chờ jobs đang chạy hoàn thành
/engineering-skills:senior-security
Thực hiện security audit cho project:
- Kiểm tra tất cả endpoints có authentication/authorization đúng không
- Tìm potential SQL injection, XSS, CSRF vulnerabilities
- Kiểm tra secret management (có hardcode secrets không?)
- Review CORS configuration
- Kiểm tra rate limiting
- Đánh giá password policy
- Kiểm tra file upload validation
- Đề xuất fixes theo mức độ nghiêm trọng (Critical, High, Medium, Low)
Cấu hình Helmet.js chi tiết:
- Content-Security-Policy: chặn inline scripts, chỉ cho phép trusted sources
- X-Content-Type-Options: nosniff
- X-Frame-Options: DENY (chống clickjacking)
- Strict-Transport-Security: max-age=31536000; includeSubDomains
- Referrer-Policy: strict-origin-when-cross-origin
- Permissions-Policy: disable camera, microphone, geolocation
- CORS: whitelist specific origins, methods, headers
- Custom headers cho API versioning
Implement input validation và sanitization toàn diện:
1. Zod schemas cho mỗi endpoint (body, query, params)
2. Validation middleware tự động parse và validate
3. Sanitization:
- Strip HTML tags từ text inputs
- Escape special characters
- Trim whitespace
- Normalize email (lowercase)
- Remove null bytes
4. File upload validation:
- Magic bytes check (không chỉ dựa vào extension)
- File size limits per type
- Virus scanning integration (ClamAV)
5. Rate limiting per endpoint:
- Login: 5 requests / 15 phút
- Register: 3 requests / 1 giờ
- API general: 100 requests / phút
- File upload: 10 requests / phút
Kiểm tra và tăng cường bảo vệ SQL Injection và XSS:
- Đảm bảo tất cả queries dùng parameterized queries (Prisma đã handle)
- Review các chỗ dùng $queryRaw - phải dùng Prisma.sql template tag
- DOMPurify cho user-generated HTML content
- Output encoding cho API responses
- CSP headers chống XSS
- HttpOnly + Secure + SameSite cookies
- Tạo integration tests cho các attack vectors phổ biến
Kiểm tra bảo mật dependencies:
- Chạy npm audit và fix vulnerabilities
- Kiểm tra licenses compatibility
- Tìm deprecated packages và đề xuất thay thế
- Setup Dependabot hoặc Renovate Bot
- Lock file integrity check
- Loại bỏ unused dependencies
Tạo Swagger documentation cho toàn bộ API:
- Sử dụng swagger-jsdoc + swagger-ui-express
- Hoặc: tạo OpenAPI 3.0 spec file (YAML) thủ công
- Document tất cả endpoints: path, method, description, request body, response, errors
- Authentication schemes: Bearer token, API key
- Request/Response examples cho mỗi endpoint
- Enum values với mô tả
- Serve tại /api/docs
- Export spec tại /api/docs/json
Tạo Postman collection cho project:
- Tổ chức theo folders: Auth, Users, Products, Orders
- Environment variables: baseUrl, accessToken, refreshToken
- Pre-request scripts: tự động attach auth token
- Tests scripts: tự động save tokens từ login response
- Ví dụ request/response cho mỗi endpoint
- Collection runner test sequence
- Export file JSON để team sử dụng
Tạo README.md chi tiết cho project:
- Giới thiệu ngắn gọn
- Tech stack
- Yêu cầu hệ thống (Node.js version, PostgreSQL, Redis)
- Hướng dẫn cài đặt (clone, install, setup env, migrate, seed)
- Chạy development server
- Chạy tests
- Cấu trúc thư mục và giải thích
- API endpoints overview
- Environment variables reference
- Docker setup
- Deployment guide
- Contributing guidelines
- License
Thêm JSDoc comments cho các module quan trọng:
- Tất cả public functions trong services
- Interfaces và types
- Complex utility functions
- Middleware functions
- Config files
- Format: description, @param, @returns, @throws, @example
Cấu hình build production tối ưu:
1. tsconfig.build.json (extend tsconfig.json):
- Exclude tests, mocks, scripts
- Generate source maps cho debugging
- Generate declaration files
- Strip comments
2. Build script:
- Clean dist/ trước khi build
- Compile TypeScript
- Copy non-TS files (templates, static assets)
- Generate build info (version, commit hash, build time)
3. Production optimizations:
- NODE_ENV=production
- Enable V8 optimizations
- Memory limits configuration
- Cluster mode với PM2
Tạo Dockerfile multi-stage build tối ưu:
Stage 1 (builder):
- Node.js 20 Alpine
- Install dependencies (cả devDependencies)
- Build TypeScript
- Prune devDependencies
Stage 2 (production):
- Node.js 20 Alpine
- Copy chỉ node_modules (production) và dist/
- Non-root user
- Health check
- Expose port
- Tối ưu image size (dưới 200MB)
docker-compose.yml:
- App service
- PostgreSQL service
- Redis service
- Volumes cho persistence
- Networks isolation
- Environment files
Tạo hệ thống quản lý environment config:
- Dùng dotenv + Zod validation cho env vars
- Config object typed với TypeScript
- Validation khi startup: fail fast nếu thiếu biến quan trọng
- Các environments: development, test, staging, production
- .env.example với mô tả từng biến
- Config cho: database, redis, jwt, email, storage, cors, logging
- Không commit .env files
- Docker secrets support cho production
Tạo GitHub Actions CI/CD pipeline:
1. CI (trên mọi PR):
- Install dependencies
- Lint check
- Type check (tsc --noEmit)
- Unit tests
- Integration tests (với PostgreSQL service container)
- Build check
- Coverage report comment trên PR
2. CD (khi merge vào main):
- Build Docker image
- Push lên Container Registry
- Deploy lên staging
- Smoke tests
- Deploy lên production (manual approval)
- Notify Slack/Discord
3. Scheduled:
- Dependency audit hàng tuần
- Full test suite hàng đêm
Tạo cấu hình PM2 cho production:
- ecosystem.config.js
- Cluster mode: instances = max CPUs
- Auto-restart khi crash
- Memory limit restart (500MB)
- Log management: combined + error logs
- Graceful reload (zero-downtime)
- Watch mode cho development
- Environment-specific config
- Startup script
Dưới đây là các prompt mẫu cho những tình huống phổ biến khi phát triển dự án Node.js/TypeScript:
Thêm tính năng "Quản lý danh mục sản phẩm" (Category):
- Model: id, name, slug, description, parentId (nullable, tự tham chiếu cho nested categories), isActive, sortOrder, createdAt, updatedAt
- API: CRUD endpoints tại /api/categories
- Hỗ trợ nested categories (tree structure) tối đa 3 cấp
- GET endpoint trả về dạng tree
- Validation: name required, slug auto-generate từ name, parentId phải valid
- Migration + Seed 10 categories mẫu
- Unit tests cho service, API tests cho endpoints
Sửa lỗi: API GET /api/products trả về 500 khi query param "minPrice" là string không phải số.
Yêu cầu:
- Tìm nguyên nhân root cause
- Fix validation cho query params
- Trả về 400 Bad Request với message rõ ràng thay vì 500
- Thêm test case cho trường hợp này
- Kiểm tra các endpoints khác có lỗi tương tự không
Refactor module User:
- Tách UserService thành các service nhỏ hơn: UserAuthService, UserProfileService, UserAdminService
- Extract validation logic ra Zod schemas riêng
- Loại bỏ code trùng lặp giữa các controllers
- Thêm TypeScript strict types cho tất cả parameters và return values
- Đảm bảo tất cả tests vẫn pass sau khi refactor
- Không thay đổi API contract (endpoints và response format giữ nguyên)
API GET /api/products đang chậm (response time > 2s khi có 10,000 products):
- Phân tích bottleneck (query, serialization, network?)
- Thêm database indexes cần thiết
- Implement Redis caching cho list endpoint
- Optimize Prisma query: chỉ select fields cần thiết
- Thêm cursor-based pagination thay vì offset
- Benchmark trước và sau tối ưu
- Target: response time < 200ms
Tích hợp gửi email với Resend (hoặc Nodemailer + SMTP):
- EmailService với các methods: sendVerification, sendPasswordReset, sendWelcome, sendNotification
- HTML email templates với handlebars
- Queue emails qua BullMQ (không block request)
- Retry logic: tối đa 3 lần, delay exponential
- Template variables injection
- Development mode: log email content thay vì gửi thật
- Types cho template data
Tạo module Image Processing:
- Upload ảnh lên S3 (hoặc local storage cho dev)
- Resize ảnh: thumbnail (150x150), medium (600x400), large (1200x800)
- Sử dụng Sharp cho image processing
- Xử lý async bằng background job
- Trả về URLs cho tất cả kích thước
- Xóa ảnh cũ khi update
- Validate: chỉ cho phép jpg, png, webp, tối đa 5MB
- Convert tất cả sang webp để tiết kiệm dung lượng
Tạo hệ thống scheduled tasks:
- Sử dụng node-cron hoặc BullMQ repeatable jobs
- Tasks:
+ Xóa refresh tokens hết hạn (chạy mỗi ngày lúc 2:00 AM)
+ Gửi email nhắc nhở cho users chưa verify (sau 24h đăng ký)
+ Generate báo cáo thống kê hàng tuần
+ Backup database metadata
+ Cleanup temp files older than 7 days
- Logging cho mỗi task run
- Error notification nếu task fail
- Dashboard endpoint xem trạng thái các tasks
Thực hiện data migration: thêm field "fullName" vào User model:
1. Thêm field fullName (String, nullable) vào Prisma schema
2. Tạo migration
3. Viết script migration: set fullName = firstName + " " + lastName cho tất cả users hiện tại
4. Update API: trả về fullName, accept fullName khi create/update
5. Deprecate firstName, lastName (vẫn giữ nhưng đánh dấu deprecated)
6. Update tests
7. Update Swagger docs
Thêm monitoring vào project:
- Prometheus metrics endpoint (/metrics):
+ HTTP request duration histogram
+ Request count by status code
+ Active connections gauge
+ Database query duration
+ Cache hit/miss ratio
+ Memory and CPU usage
- Sử dụng prom-client
- Grafana dashboard config (JSON export)
- Alerting rules cho: error rate > 5%, response time > 1s, memory > 80%
Tạo hệ thống notification realtime:
- WebSocket server với Socket.IO
- Events:
+ notification:new - server gửi notification mới cho user
+ notification:read - user đánh dấu đã đọc
+ notification:readAll - đánh dấu tất cả đã đọc
- REST API:
+ GET /api/notifications - danh sách notifications (pagination)
+ GET /api/notifications/unread-count - số chưa đọc
+ PATCH /api/notifications/:id/read - đánh dấu đã đọc
- Database: Notification model (userId, type, title, content, data JSON, isRead, createdAt)
- Trigger notifications từ các events khác (new comment, new follower, etc.)
Chuyển đổi app sang multi-tenant architecture:
- Strategy: schema-based (mỗi tenant 1 schema PostgreSQL)
- Tenant middleware: xác định tenant từ subdomain hoặc header X-Tenant-ID
- Prisma client factory: tạo client cho đúng schema
- Tenant management API: tạo/xóa tenant, migrate schema
- Shared data vs tenant-specific data
- Cross-tenant queries cho super admin
Tạo GraphQL API song song với REST API hiện tại:
- Apollo Server integration với Express
- Type definitions từ Prisma schema
- Resolvers cho: User, Post, Comment, Category
- Authentication directive: @auth, @hasRole(role: ADMIN)
- DataLoader cho N+1 prevention
- Pagination: Relay cursor-based connection spec
- Subscriptions cho realtime updates
- Playground/Explorer tại /graphql
Server bị crash với error "ECONNREFUSED" khi kết nối PostgreSQL:
- Kiểm tra database connection string trong .env
- Kiểm tra PostgreSQL service có đang chạy không
- Kiểm tra network/firewall
- Thêm connection retry logic với exponential backoff
- Thêm graceful error handling: không crash app, trả về 503 Service Unavailable
- Health check endpoint phản ánh database connection status
Chuẩn bị deploy lên production (VPS với Docker):
- Dockerfile production-ready (multi-stage, non-root, healthcheck)
- docker-compose.production.yml (app, postgres, redis, nginx)
- Nginx reverse proxy config (SSL, gzip, rate limiting, caching static)
- Let's Encrypt SSL auto-renewal
- Environment variables management
- Database backup script (chạy hàng ngày)
- Zero-downtime deployment script
- Monitoring setup (Prometheus + Grafana)
- Log rotation config
Khi làm việc với Claude Code, luôn cung cấp đủ ngữ cảnh:
# Thay vì
Thêm endpoint mới
# Hãy nói rõ
Thêm endpoint GET /api/reports/monthly cho module Reports:
- Query params: year (required), month (required)
- Response: tổng doanh thu, số đơn hàng, top 5 sản phẩm bán chạy
- Chỉ ADMIN và MANAGER mới truy cập được
- Cache response trong Redis 1 giờ
- Thêm vào Swagger docs
# Khi gặp lỗi, cung cấp đầy đủ thông tin
Lỗi khi chạy npm run dev:
Error: Cannot find module '@config/database'
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:1048:15)
at Function.Module._load (node:internal/modules/cjs/loader:901:27)
File tsconfig.json đã cấu hình path alias @config → src/config.
Hãy kiểm tra và sửa lỗi này.
# Trước khi bắt đầu feature lớn
/engineering-skills:senior-architect
# Khi cần review code
/code-review
# Khi cần kiểm tra bảo mật
/engineering-skills:senior-security
# Khi viết tests
/engineering-skills:senior-qa
# Khi tối ưu performance
/engineering-skills:senior-backend
# Khi cần help với DevOps
/engineering-skills:senior-devops
Quy trình phát triển 1 feature mới với Claude Code:
# 1. Phân tích yêu cầu
claude "Phân tích yêu cầu feature X, liệt kê các tasks cần làm"
# 2. Thiết kế
claude "Thiết kế database schema và API endpoints cho feature X"
# 3. Implement
claude "Implement feature X theo thiết kế vừa thống nhất"
# 4. Testing
claude "Viết unit tests và integration tests cho feature X"
# 5. Review
claude "/code-review"
claude "/engineering-skills:senior-security"
# 6. Documentation
claude "Cập nhật Swagger docs và README cho feature X"
# 7. Commit
claude "/commit"
Tài liệu này được thiết kế để hướng dẫn từ zero đến production cho dự án Node.js/TypeScript. Mỗi phần có thể được sử dụng độc lập hoặc theo tuần tự.