NestJS Framework Skills
This skill collection provides comprehensive guidance for building applications with NestJS, a progressive Node.js framework for building efficient, scalable server-side applications.
Available Skills
Core Concepts
These skills cover the fundamental building blocks of every NestJS application:
- basics - Project setup, installation, CLI usage, and core architecture concepts
- controllers - HTTP request handling, routing, route parameters, query parameters, and request payloads
- providers - Services, dependency injection, and the IoC container
- modules - Application organization, feature modules, shared modules, and dynamic modules
- middleware - Request/response preprocessing, logging, and authentication middleware
- guards - Route protection, authorization, and role-based access control
- interceptors - Response transformation, logging, caching, and timeout handling
- pipes - Data validation and transformation with class-validator
- exception-filters - Error handling and custom exception responses
- custom-decorators - Creating reusable decorators for parameters, metadata, and composition
Fundamentals
Advanced topics for mastering NestJS architecture:
- dependency-injection - Custom providers, factory providers, async providers, and injection scopes
- testing - Unit testing, integration testing, E2E testing, and mocking strategies
- lifecycle - Lifecycle hooks for modules, providers, and application bootstrapping
Techniques
Practical techniques for common application requirements:
- configuration - Environment variables, configuration validation, and custom config files
- validation - Request validation with class-validator and ValidationPipe
- database - SQL databases with TypeORM/Prisma and MongoDB with Mongoose
- caching - In-memory and Redis caching strategies
- task-scheduling - Cron jobs, intervals, and dynamic task scheduling
- queues - Background job processing with Bull and Redis
Security
Security best practices and authentication/authorization:
- authentication - JWT authentication, Passport integration, and auth strategies
- authorization - Role-based access control (RBAC) and permission-based authorization
- security - CORS, CSRF protection, Helmet, rate limiting, and encryption
Advanced Topics
Advanced features for building complex applications:
- graphql - GraphQL integration, resolvers, queries, mutations, and subscriptions
- websockets - Real-time communication with WebSocket gateways
- microservices - Microservices architecture with various transport layers (TCP, Redis, NATS, Kafka, gRPC)
- cli - NestJS CLI commands, code generation, and project scaffolding
- openapi - API documentation with Swagger/OpenAPI
Quick Reference
Request Processing Pipeline
Incoming Request
↓
Middleware ──────────── Global → Module → Route
↓
Guards ─────────────── Global → Controller → Route
↓
Interceptors (before) ── Global → Controller → Route
↓
Pipes ──────────────── Global → Controller → Route → Parameter
↓
Route Handler ───────── Controller Method
↓
Interceptors (after) ─── Route → Controller → Global
↓
Exception Filters ────── Route → Controller → Global
↓
Response
Common CLI Commands
# Installation
npm i -g @nestjs/cli
nest new project-name
# Code Generation
nest generate module users
nest generate controller users
nest generate service users
nest generate resource users # Generates module, controller, service, DTOs
# Running
npm run start:dev # Development mode with watch
npm run start:debug # Debug mode
npm run start:prod # Production mode
# Testing
npm run test # Unit tests
npm run test:watch # Unit tests with watch
npm run test:cov # Coverage
npm run test:e2e # End-to-end tests
# Building
npm run build # Production build
Architecture Patterns
Feature Module Pattern
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UsersController],
providers: [UsersService, UsersRepository],
exports: [UsersService],
})
export class UsersModule {}
Service Layer Pattern
@Injectable()
export class UsersService {
constructor(
private readonly repository: UsersRepository,
private readonly emailService: EmailService,
) {}
async create(dto: CreateUserDto): Promise<User> {
const user = await this.repository.create(dto);
await this.emailService.sendWelcome(user.email);
return user;
}
}
Controller Pattern
@Controller('users')
export class UsersController {
constructor(private readonly service: UsersService) {}
@Get()
findAll(@Query() query: QueryDto) {
return this.service.findAll(query);
}
@Post()
@UseGuards(JwtAuthGuard)
create(@Body() dto: CreateUserDto) {
return this.service.create(dto);
}
}
Dependency Injection Patterns
// Standard injection
constructor(private readonly service: MyService) {}
// Custom token injection
constructor(@Inject('CONFIG') private config: Config) {}
// Optional dependency
constructor(@Optional() private logger?: Logger) {}
// Multiple providers with same token
constructor(@Inject('FEATURES') private features: Feature[]) {}
Validation Pattern
import { IsString, IsInt, Min, Max, IsEmail } from 'class-validator';
export class CreateUserDto {
@IsString()
@Length(3, 50)
name: string;
@IsEmail()
email: string;
@IsInt()
@Min(0)
@Max(120)
age: number;
}
// Use globally
app.useGlobalPipes(new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}));
Authentication Pattern
// JWT Strategy
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(config: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: config.get('JWT_SECRET'),
});
}
validate(payload: any) {
return { userId: payload.sub, username: payload.username };
}
}
// Protected Route
@Controller('profile')
@UseGuards(JwtAuthGuard)
export class ProfileController {
@Get()
getProfile(@Request() req) {
return req.user;
}
}
Best Practices
General Architecture
- One feature per module - Keep related code together
- Thin controllers - Delegate business logic to services
- Use DTOs - Define data transfer objects for validation
- Dependency injection - Inject all dependencies via constructor
- Separation of concerns - Controllers → Services → Repositories
Code Organization
- Feature-based structure - Organize by feature, not by layer
- Shared modules - Create common modules for reusable functionality
- Clear naming - Use descriptive names (UsersService, not Service1)
- Consistent patterns - Follow the same patterns throughout
Performance
- Use singleton scope - Default scope for most providers
- Enable caching - Cache frequently accessed data
- Use Fastify - For better performance than Express
- Database optimization - Use indexes, eager/lazy loading wisely
- Async operations - Use async/await for I/O operations
Security
- Validate all input - Use ValidationPipe globally
- Sanitize data - Prevent XSS and SQL injection
- Use HTTPS - Enable SSL/TLS in production
- Rate limiting - Prevent abuse
- Security headers - Use Helmet middleware
- Authentication - Implement proper auth (JWT, OAuth)
- Authorization - Protect routes with guards
Testing
- Write unit tests - Test services and business logic
- Integration tests - Test module interactions
- E2E tests - Test complete user flows
- Mock dependencies - Isolate units being tested
- Test coverage - Aim for >80% coverage
Error Handling
- Use built-in exceptions - BadRequestException, NotFoundException, etc.
- Custom exception filters - For consistent error responses
- Logging - Log errors with context
- Graceful degradation - Handle failures gracefully
- Validation errors - Return clear validation messages
Resources
Getting Started
If you're new to NestJS, start with these skills in order:
- basics - Set up your first project
- controllers - Create API endpoints
- providers - Add business logic
- modules - Organize your application
- validation - Validate request data
- authentication - Secure your API
- database - Connect to a database
Then explore the other skills based on your application's needs.
1---2name: nestjs3description: Comprehensive NestJS framework skills covering controllers, providers, modules, middleware, guards, interceptors, pipes, validation, authentication, GraphQL, microservices, and more. Use when working with NestJS applications.4---56# NestJS Framework Skills78This skill collection provides comprehensive guidance for building applications with NestJS, a progressive Node.js framework for building efficient, scalable server-side applications.910## Available Skills1112### Core Concepts1314These skills cover the fundamental building blocks of every NestJS application:1516- **[basics](skills/basics/SKILL.md)** - Project setup, installation, CLI usage, and core architecture concepts17- **[controllers](skills/controllers/SKILL.md)** - HTTP request handling, routing, route parameters, query parameters, and request payloads18- **[providers](skills/providers/SKILL.md)** - Services, dependency injection, and the IoC container19- **[modules](skills/modules/SKILL.md)** - Application organization, feature modules, shared modules, and dynamic modules20- **[middleware](skills/middleware/SKILL.md)** - Request/response preprocessing, logging, and authentication middleware21- **[guards](skills/guards/SKILL.md)** - Route protection, authorization, and role-based access control22- **[interceptors](skills/interceptors/SKILL.md)** - Response transformation, logging, caching, and timeout handling23- **[pipes](skills/pipes/SKILL.md)** - Data validation and transformation with class-validator24- **[exception-filters](skills/exception-filters/SKILL.md)** - Error handling and custom exception responses25- **[custom-decorators](skills/custom-decorators/SKILL.md)** - Creating reusable decorators for parameters, metadata, and composition2627### Fundamentals2829Advanced topics for mastering NestJS architecture:3031- **[dependency-injection](skills/dependency-injection/SKILL.md)** - Custom providers, factory providers, async providers, and injection scopes32- **[testing](skills/testing/SKILL.md)** - Unit testing, integration testing, E2E testing, and mocking strategies33- **[lifecycle](skills/lifecycle/SKILL.md)** - Lifecycle hooks for modules, providers, and application bootstrapping3435### Techniques3637Practical techniques for common application requirements:3839- **[configuration](skills/configuration/SKILL.md)** - Environment variables, configuration validation, and custom config files40- **[validation](skills/validation/SKILL.md)** - Request validation with class-validator and ValidationPipe41- **[database](skills/database/SKILL.md)** - SQL databases with TypeORM/Prisma and MongoDB with Mongoose42- **[caching](skills/caching/SKILL.md)** - In-memory and Redis caching strategies43- **[task-scheduling](skills/task-scheduling/SKILL.md)** - Cron jobs, intervals, and dynamic task scheduling44- **[queues](skills/queues/SKILL.md)** - Background job processing with Bull and Redis4546### Security4748Security best practices and authentication/authorization:4950- **[authentication](skills/authentication/SKILL.md)** - JWT authentication, Passport integration, and auth strategies51- **[authorization](skills/authorization/SKILL.md)** - Role-based access control (RBAC) and permission-based authorization52- **[security](skills/security/SKILL.md)** - CORS, CSRF protection, Helmet, rate limiting, and encryption5354### Advanced Topics5556Advanced features for building complex applications:5758- **[graphql](skills/graphql/SKILL.md)** - GraphQL integration, resolvers, queries, mutations, and subscriptions59- **[websockets](skills/websockets/SKILL.md)** - Real-time communication with WebSocket gateways60- **[microservices](skills/microservices/SKILL.md)** - Microservices architecture with various transport layers (TCP, Redis, NATS, Kafka, gRPC)61- **[cli](skills/cli/SKILL.md)** - NestJS CLI commands, code generation, and project scaffolding62- **[openapi](skills/openapi/SKILL.md)** - API documentation with Swagger/OpenAPI6364## Quick Reference6566### Request Processing Pipeline6768```69Incoming Request70 ↓71Middleware ──────────── Global → Module → Route72 ↓73Guards ─────────────── Global → Controller → Route74 ↓75Interceptors (before) ── Global → Controller → Route76 ↓77Pipes ──────────────── Global → Controller → Route → Parameter78 ↓79Route Handler ───────── Controller Method80 ↓81Interceptors (after) ─── Route → Controller → Global82 ↓83Exception Filters ────── Route → Controller → Global84 ↓85Response86```8788### Common CLI Commands8990```bash91# Installation92npm i -g @nestjs/cli93nest new project-name9495# Code Generation96nest generate module users97nest generate controller users98nest generate service users99nest generate resource users # Generates module, controller, service, DTOs100101# Running102npm run start:dev # Development mode with watch103npm run start:debug # Debug mode104npm run start:prod # Production mode105106# Testing107npm run test # Unit tests108npm run test:watch # Unit tests with watch109npm run test:cov # Coverage110npm run test:e2e # End-to-end tests111112# Building113npm run build # Production build114```115116### Architecture Patterns117118#### Feature Module Pattern119```typescript120@Module({121 imports: [TypeOrmModule.forFeature([User])],122 controllers: [UsersController],123 providers: [UsersService, UsersRepository],124 exports: [UsersService],125})126export class UsersModule {}127```128129#### Service Layer Pattern130```typescript131@Injectable()132export class UsersService {133 constructor(134 private readonly repository: UsersRepository,135 private readonly emailService: EmailService,136 ) {}137138 async create(dto: CreateUserDto): Promise<User> {139 const user = await this.repository.create(dto);140 await this.emailService.sendWelcome(user.email);141 return user;142 }143}144```145146#### Controller Pattern147```typescript148@Controller('users')149export class UsersController {150 constructor(private readonly service: UsersService) {}151152 @Get()153 findAll(@Query() query: QueryDto) {154 return this.service.findAll(query);155 }156157 @Post()158 @UseGuards(JwtAuthGuard)159 create(@Body() dto: CreateUserDto) {160 return this.service.create(dto);161 }162}163```164165### Dependency Injection Patterns166167```typescript168// Standard injection169constructor(private readonly service: MyService) {}170171// Custom token injection172constructor(@Inject('CONFIG') private config: Config) {}173174// Optional dependency175constructor(@Optional() private logger?: Logger) {}176177// Multiple providers with same token178constructor(@Inject('FEATURES') private features: Feature[]) {}179```180181### Validation Pattern182183```typescript184import { IsString, IsInt, Min, Max, IsEmail } from 'class-validator';185186export class CreateUserDto {187 @IsString()188 @Length(3, 50)189 name: string;190191 @IsEmail()192 email: string;193194 @IsInt()195 @Min(0)196 @Max(120)197 age: number;198}199200// Use globally201app.useGlobalPipes(new ValidationPipe({202 whitelist: true,203 forbidNonWhitelisted: true,204 transform: true,205}));206```207208### Authentication Pattern209210```typescript211// JWT Strategy212@Injectable()213export class JwtStrategy extends PassportStrategy(Strategy) {214 constructor(config: ConfigService) {215 super({216 jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),217 secretOrKey: config.get('JWT_SECRET'),218 });219 }220221 validate(payload: any) {222 return { userId: payload.sub, username: payload.username };223 }224}225226// Protected Route227@Controller('profile')228@UseGuards(JwtAuthGuard)229export class ProfileController {230 @Get()231 getProfile(@Request() req) {232 return req.user;233 }234}235```236237## Best Practices238239### General Architecture2401. **One feature per module** - Keep related code together2412. **Thin controllers** - Delegate business logic to services2423. **Use DTOs** - Define data transfer objects for validation2434. **Dependency injection** - Inject all dependencies via constructor2445. **Separation of concerns** - Controllers → Services → Repositories245246### Code Organization2471. **Feature-based structure** - Organize by feature, not by layer2482. **Shared modules** - Create common modules for reusable functionality2493. **Clear naming** - Use descriptive names (UsersService, not Service1)2504. **Consistent patterns** - Follow the same patterns throughout251252### Performance2531. **Use singleton scope** - Default scope for most providers2542. **Enable caching** - Cache frequently accessed data2553. **Use Fastify** - For better performance than Express2564. **Database optimization** - Use indexes, eager/lazy loading wisely2575. **Async operations** - Use async/await for I/O operations258259### Security2601. **Validate all input** - Use ValidationPipe globally2612. **Sanitize data** - Prevent XSS and SQL injection2623. **Use HTTPS** - Enable SSL/TLS in production2634. **Rate limiting** - Prevent abuse2645. **Security headers** - Use Helmet middleware2656. **Authentication** - Implement proper auth (JWT, OAuth)2667. **Authorization** - Protect routes with guards267268### Testing2691. **Write unit tests** - Test services and business logic2702. **Integration tests** - Test module interactions2713. **E2E tests** - Test complete user flows2724. **Mock dependencies** - Isolate units being tested2735. **Test coverage** - Aim for >80% coverage274275### Error Handling2761. **Use built-in exceptions** - BadRequestException, NotFoundException, etc.2772. **Custom exception filters** - For consistent error responses2783. **Logging** - Log errors with context2794. **Graceful degradation** - Handle failures gracefully2805. **Validation errors** - Return clear validation messages281282## Resources283284- **Official Documentation**: https://docs.nestjs.com/285- **GitHub Repository**: https://github.com/nestjs/nest286- **Discord Community**: https://discord.gg/nestjs287- **Awesome NestJS**: https://github.com/nestjs/awesome-nestjs288289## Getting Started290291If you're new to NestJS, start with these skills in order:2922931. **[basics](skills/basics/SKILL.md)** - Set up your first project2942. **[controllers](skills/controllers/SKILL.md)** - Create API endpoints2953. **[providers](skills/providers/SKILL.md)** - Add business logic2964. **[modules](skills/modules/SKILL.md)** - Organize your application2975. **[validation](skills/validation/SKILL.md)** - Validate request data2986. **[authentication](skills/authentication/SKILL.md)** - Secure your API2997. **[database](skills/database/SKILL.md)** - Connect to a database300301Then explore the other skills based on your application's needs.