plugins/developer-kit-typescript/skills/nestjs-best-practices/SKILL.md
Provides comprehensive NestJS best practices including modular architecture, dependency injection scoping, exception filters, DTO validation with class-validator, and Drizzle ORM integration. Use when designing NestJS modules, implementing providers, creating exception filters, validating DTOs, or integrating Drizzle ORM within NestJS applications.
npx skillsauth add giuseppe-trisciuoglio/developer-kit nestjs-best-practicesInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Grounded in the Official NestJS Documentation, this skill enforces modular architecture, dependency injection scoping, exception filters, DTO validation with class-validator, and Drizzle ORM integration patterns.
Follow strict module encapsulation. Each domain feature should be its own @Module():
forwardRef() only as a last resort for circular dependencies; prefer restructuringSharedModule for cross-cutting concerns (logging, configuration, caching)See references/arch-module-boundaries.md for enforcement rules.
Choose the correct provider scope based on use case:
| Scope | Lifecycle | Use Case |
|-------------|------------------------------|---------------------------------------------|
| DEFAULT | Singleton (shared) | Stateless services, repositories |
| REQUEST | Per-request instance | Request-scoped data (tenant, user context) |
| TRANSIENT | New instance per injection | Stateful utilities, per-consumer caches |
DEFAULT scope — only use REQUEST or TRANSIENT when justifieduseClass, useValue, useFactory, or useExistingSee references/di-provider-scoping.md for enforcement rules.
Understand and respect the NestJS request processing pipeline:
Middleware → Guards → Interceptors (before) → Pipes → Route Handler → Interceptors (after) → Exception Filters
true/false)Standardize error responses across the application:
HttpException for HTTP-specific errorsOrderNotFoundException)ExceptionFilter for consistent error formattingSee references/error-exception-filters.md for enforcement rules.
Enforce input validation at the API boundary:
ValidationPipe globally with transform: true and whitelist: trueclass-validator decoratorsclass-transformer for type coercion (@Type(), @Transform())See references/api-validation-dto.md for enforcement rules.
Integrate Drizzle ORM following NestJS provider conventions:
See references/db-drizzle-patterns.md for enforcement rules.
| Area | Do | Don't |
|--------------------|------------------------------------------|------------------------------------------|
| Modules | One module per domain feature | Dump everything in AppModule |
| DI Scoping | Default to singleton scope | Use REQUEST scope without justification|
| Error Handling | Custom exception filters + domain errors | Bare try/catch with console.log |
| Validation | Global ValidationPipe + DTO decorators | Manual if checks in controllers |
| Database | Repository pattern with injected client | Direct DB queries in controllers |
| Testing | Unit test services, e2e test controllers | Skip tests or test implementation details|
| Configuration | @nestjs/config with typed schemas | Hardcode values or use process.env |
When building a "Product" feature, follow this workflow:
1. Create the module with proper encapsulation:
// product/product.module.ts
@Module({
imports: [DatabaseModule],
controllers: [ProductController],
providers: [ProductService, ProductRepository],
exports: [ProductService], // Only export what others need
})
export class ProductModule {}
2. Create validated DTOs:
// product/dto/create-product.dto.ts
import { IsString, IsNumber, IsPositive, MaxLength } from 'class-validator';
export class CreateProductDto {
@IsString() @MaxLength(255) readonly name: string;
@IsNumber() @IsPositive() readonly price: number;
}
3. Service with error handling:
@Injectable()
export class ProductService {
constructor(private readonly productRepository: ProductRepository) {}
async findById(id: string): Promise<Product> {
const product = await this.productRepository.findById(id);
if (!product) throw new ProductNotFoundException(id);
return product;
}
}
4. Verify module registration:
# Check module is imported in AppModule
grep -r "ProductModule" src/app.module.ts
# Run e2e to confirm exports work
npx jest --testPathPattern="product"
REQUEST-scoped providers cascade to all dependentsforwardRef() — restructure modules to eliminate circular dependenciesValidationPipe — always validate at the API boundary with DTOs@nestjs/config with environment variablesreferences/architecture.md — Deep-dive into NestJS architectural patternsreferences/ — Individual enforcement rules with correct/incorrect examplesassets/templates/ — Starter templates for common NestJS componentsdevelopment
Provides security review capability for TypeScript/Node.js applications, validates code against XSS, injection, CSRF, JWT/OAuth2 flaws, dependency CVEs, and secrets exposure. Use when performing security audits, before deployment, reviewing authentication/authorization implementations, or ensuring OWASP compliance for Express, NestJS, and Next.js. Triggers on "security review", "check for security issues", "TypeScript security audit".
development
Provides final code cleanup after task review approval. Removes debug logs, temporary comments, dead code, optimizes imports, and improves readability. Use when asked to clean up code, polish, finalize, tidy up, remove technical debt, or prepare code for completion after review. Not for refactoring logic or fixing bugs—focused solely on cosmetic and hygiene cleanup.
tools
Ralph Wiggum-inspired automation loop for specification-driven development. Orchestrates task implementation, review, cleanup, and synchronization using a Python script. Use when: user runs /loop command, user asks to automate task implementation, user wants to iterate through spec tasks step-by-step, or user wants to run development workflow automation with context window management. One step per invocation. State machine: init → choose_task → implementation → review → fix → cleanup → sync → update_done. Supports --from-task and --to-task for task range filtering. State persisted in fix_plan.json.
testing
Creates, updates, validates, and displays the architectural DNA of a project through two shared documents: docs/specs/architecture.md (technology stack, architectural rules, security constraints, AI guardrails) and docs/specs/ontology.md (domain glossary / Ubiquitous Language). Use BEFORE brainstorm as a project setup step, or at any point in the SDD lifecycle to validate specs/tasks against architecture principles. Triggers on 'create constitution', 'update constitution', 'constitution check', 'validate against constitution', 'project principles', 'architectural guardrails', 'setup project architecture', 'define ontology'.