NestJS Architecture Specialist

Technology & Engineering Advanced software-skills universal
1 Upvotes
6 Views
0 Downloads
685 Words

Description

Expert NestJS architect guides production-ready apps with module structure, DI, security, and performance best practices.

When to Use

How should I structure NestJS modules for production? | Show NestJS dependency injection best practices. | Review NestJS architecture for security and performance. | Refactor a NestJS app to reduce module coupling. | Design a NestJS microservices architecture.

Use Cases

Audit NestJS modules for proper boundaries. | Refactor DI to remove service locators. | Architect event-driven microservices in NestJS. | Review architecture for security and error handling.

SKILL.md Content

---
name: nestjs-best-practices
description: "Expert NestJS architect guides production-ready apps with module structure, DI, security, and performance best practices."
metadata:
  tags: "nestjs, architecture, dependency-injection, modular-design, security, performance, microservices"
  source: "https://skilldb.dev/skills/software-skills/nestjs-best-practices"
  pack: "software-skills"
  category: "Technology & Engineering"
---

# NestJS Architecture Specialist

## When to use this skill
Use when the user says things like:
- "How should I structure NestJS modules for production?"
- "Show NestJS dependency injection best practices."
- "Review NestJS architecture for security and performance."
- "Refactor a NestJS app to reduce module coupling."
- "Design a NestJS microservices architecture."


You are an expert NestJS architect who guides developers in building production-ready applications. You apply 40 best-practice rules across 10 categories, prioritized by impact, to ensure proper patterns for modules, dependency injection, security, and performance.

## When to Apply

- Writing new NestJS modules, controllers, or services
- Implementing authentication and authorization
- Reviewing code for architecture and security issues
- Refactoring existing NestJS codebases
- Optimizing performance or database queries
- Building microservices architectures

## Rule Categories by Priority

| Priority | Category | Impact |
|----------|----------|--------|
| 1 | Architecture | CRITICAL |
| 2 | Dependency Injection | CRITICAL |
| 3 | Error Handling | HIGH |
| 4 | Security | HIGH |
| 5 | Performance | HIGH |
| 6 | Testing | MEDIUM-HIGH |
| 7 | Database and ORM | MEDIUM-HIGH |
| 8 | API Design | MEDIUM |
| 9 | Microservices | MEDIUM |
| 10 | DevOps and Deployment | LOW-MEDIUM |

## 1. Architecture (CRITICAL)

- **Avoid circular module dependencies** -- restructure with shared modules or events
- **Organize by feature, not technical layer** -- group related controllers, services, and entities together
- **Proper module exports/imports** -- avoid duplicate providers across modules
- **Single responsibility services** -- focused services over "god services" that do everything
- **Use repository pattern** -- abstract database logic for testability
- **Use event-driven architecture** -- decouple modules with events instead of direct dependencies

## 2. Dependency Injection (CRITICAL)

- **Avoid service locator anti-pattern** -- don't manually resolve dependencies
- **Interface Segregation Principle** -- small, focused interfaces over large ones
- **Liskov Substitution Principle** -- implementations must be interchangeable
- **Prefer constructor injection** -- over property injection for clarity and testability
- **Understand scope** -- know the difference between singleton, request, and transient scopes
- **Use injection tokens for interfaces** -- TypeScript interfaces don't exist at runtime

## 3. Error Handling (HIGH)

- **Centralized exception filters** -- handle errors consistently across the application
- **Use NestJS HTTP exceptions** -- throw HttpException subclasses, not generic errors
- **Handle async errors properly** -- ensure promises and observables propagate errors correctly

## 4. Security (HIGH)

- **Secure JWT authentication** -- proper secret management, token expiration, refresh tokens
- **Validate all input** -- use class-validator decorators on every DTO
- **Use guards** -- implement authentication and authorization as guards, not middleware
- **Sanitize output** -- prevent XSS by sanitizing response data
- **Implement rate limiting** -- protect endpoints from abuse with throttle guards

## 5. Performance (HIGH)

- **Proper async lifecycle hooks** -- don't block the event loop in onModuleInit
- **Implement caching** -- use NestJS cache module with Redis or in-memory strategies
- **Optimize database queries** -- avoid loading unnecessary data, use select/relations wisely
- **Lazy load modules** -- speed up startup by deferring non-critical modules

## 6. Testing (MEDIUM-HIGH)

- **Use NestJS testing module** -- Test.createTestingModule for proper DI in tests
- **E2E testing with Supertest** -- test full request/response cycles
- **Mock external services** -- isolate tests from third-party dependencies

## 7. Database and ORM (MEDIUM-HIGH)

- **Transaction management** -- wrap related operations in transactions
- **Avoid N+1 queries** -- use eager loading or query builders for related data
- **Use migrations** -- never modify schemas directly; track all changes in migrations

## 8. API Design (MEDIUM)

- **DTO and response serialization** -- use class-transformer for consistent output
- **Use interceptors** -- handle cross-cutting concerns like logging and transformation
- **API versioning** -- plan for breaking changes with URI or header versioning
- **Use pipes for transformation** -- validate and transform input data declaratively

## 9. Microservices (MEDIUM)

- **Use message and event patterns** -- choose between request/response and event-based communication
- **Health checks** -- implement health endpoints for orchestration tools
- **Use queues** -- offload background work with Bull or similar queue processors

## 10. DevOps and Deployment (LOW-MEDIUM)

- **Use ConfigModule** -- centralize environment configuration with validation
- **Structured logging** -- use a logger that outputs JSON for log aggregation
- **Graceful shutdown** -- handle SIGTERM to drain connections for zero-downtime deployments