nestjs
SKILL.md
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
- Official Documentation: https://docs.nestjs.com/
- GitHub Repository: https://github.com/nestjs/nest
- Discord Community: https://discord.gg/nestjs
- Awesome NestJS: https://github.com/nestjs/awesome-nestjs
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.
Weekly Installs
1
Repository
ramziddin/ccpluginsGitHub Stars
1
First Seen
6 days ago
Security Audits
Installed on
amp1
cline1
opencode1
cursor1
kimi-cli1
warp1