nestjs-best-practices
NestJS best practices and patterns for building scalable, maintainable backend applications. This skill should be used when writing, reviewing, or refactoring NestJS code to ensure proper architecture, security, performance, and code quality. Triggers on tasks involving NestJS modules, controllers, services, guards, pipes, middleware, Prisma database operations, authentication, or any NestJS-specific patterns.
What this skill does
# NestJS Best Practices 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. ## 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 ## Rule Categories by Priority | Priority | Category | Impact | Prefix | |----------|----------|--------|--------| | 1 | Security | CRITICAL | `security-` | | 2 | Performance | HIGH | `performance-` | | 3 | Architecture | HIGH | `architecture-` | | 4 | Error Handling | HIGH | `error-handling-` | | 5 | Validation | CRITICAL | `validation-` | | 6 | Database | CRITICAL | `database-` | | 7 | Authentication | CRITICAL | `auth-` | | 8 | API | MEDIUM | `api-` | | 9 | Configuration | CRITICAL | `config-` | | 10 | Testing | MEDIUM | `testing-` | | 11 | Deployment | MEDIUM | `deployment-` | | 12 | Middleware | MEDIUM | `middleware-` | | 13 | Advanced | HIGH | `advanced-` | ## Quick Reference ### 1. Security (CRITICAL) - `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 ### 2. Performance (HIGH) - `performance-redis-caching` - Cache frequently used data with Redis ### 3. Architecture (HIGH) - `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 ### 4. Error Handling (HIGH) - `error-handling-exception-filter` - Enable global exception filter - `error-handling-structured-logging` - Implement proper logging strategy ### 5. Validation (CRITICAL) - `validation-custom-pipes` - Create custom pipes for query parameter transformation - `validation-dto-validation` - Validate all inputs with DTOs and ValidationPipe ### 6. Database (CRITICAL) - `database-parameterized-queries` - Use parameterized queries to prevent SQL injection (Prisma v7) ### 7. Authentication (CRITICAL) - `auth-password-hashing` - Use Bun's built-in Crypto for secure password hashing (argon2/bcrypt) - `auth-route-guards` - Use guards for route protection ### 8. API (MEDIUM) - `api-cursor-pagination` - Use cursor-based pagination for large datasets - `api-swagger-docs` - Generate Swagger/OpenAPI documentation ### 9. Configuration (CRITICAL) - `config-no-secrets` - Never hardcode secrets - use environment variables ### 10. Testing (MEDIUM) - `testing-unit-tests` - Write comprehensive unit tests ### 11. Deployment (MEDIUM) - `deployment-health-checks` - Implement health check endpoints ### 12. Middleware (MEDIUM) - `middleware-compression` - Enable compression middleware for responses - `middleware-rate-limiting` - Implement rate limiting for all routes ### 13. Advanced (HIGH) - `advanced-lazy-loading` - Lazy load non-critical modules - `advanced-scheduled-tasks` - Use @nestjs/schedule for cron jobs and 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.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 ## Key Patterns ### Agent-Friendly Format 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 ### 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 ## Full Compiled Document For the complete guide with all rules expanded: `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 ``` ## 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
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.