NestJS Core Knowledge
Deep Knowledge: Use mcp__documentation__fetch_docs with technology: nestjs for comprehensive documentation.
Module Structure
// users.module.ts
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}
Controller
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Get()
findAll(): Promise<User[]> {
return this.usersService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string): Promise<User> {
return this.usersService.findOne(id);
}
@Post()
@HttpCode(201)
create(@Body() createUserDto: CreateUserDto): Promise<User> {
return this.usersService.create(createUserDto);
}
@Put(':id')
update(@Param('id') id: string, @Body() dto: UpdateUserDto) {
return this.usersService.update(id, dto);
}
@Delete(':id')
@HttpCode(204)
remove(@Param('id') id: string) {
return this.usersService.remove(id);
}
}
Service
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>,
) {}
findAll(): Promise<User[]> {
return this.usersRepository.find();
}
findOne(id: string): Promise<User | null> {
return this.usersRepository.findOneBy({ id });
}
}
Key Decorators
| Decorator |
Purpose |
@Module |
Define module |
@Controller |
Define controller |
@Injectable |
Mark as provider |
@Get/@Post/@Put/@Delete |
HTTP methods |
@Body/@Param/@Query |
Request data |
@UseGuards |
Apply guards |
@UsePipes |
Apply pipes |
Production Readiness
Security Configuration
// main.ts - Security setup
import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import helmet from 'helmet';
import * as compression from 'compression';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Security headers
app.use(helmet());
// CORS configuration
app.enableCors({
origin: process.env.ALLOWED_ORIGINS?.split(',') || [],
credentials: true,
});
// Global validation pipe
app.useGlobalPipes(new ValidationPipe({
whitelist: true, // Strip non-whitelisted properties
forbidNonWhitelisted: true, // Throw on non-whitelisted
transform: true, // Auto-transform payloads
}));
// Response compression
app.use(compression());
// Rate limiting (with @nestjs/throttler)
// Configured in AppModule
await app.listen(process.env.PORT || 3000);
}
// Rate limiting module
import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler';
import { APP_GUARD } from '@nestjs/core';
@Module({
imports: [
ThrottlerModule.forRoot([{
ttl: 60000, // 1 minute
limit: 100, // 100 requests per minute
}]),
],
providers: [{
provide: APP_GUARD,
useClass: ThrottlerGuard,
}],
})
export class AppModule {}
Health Checks
// health.controller.ts
import { Controller, Get } from '@nestjs/common';
import { HealthCheck, HealthCheckService, HttpHealthIndicator, TypeOrmHealthIndicator } from '@nestjs/terminus';
@Controller('health')
export class HealthController {
constructor(
private health: HealthCheckService,
private http: HttpHealthIndicator,
private db: TypeOrmHealthIndicator,
) {}
@Get()
@HealthCheck()
check() {
return this.health.check([
() => this.db.pingCheck('database'),
]);
}
@Get('ready')
@HealthCheck()
readiness() {
return this.health.check([
() => this.db.pingCheck('database'),
() => this.http.pingCheck('external-api', 'https://api.example.com/health'),
]);
}
}
Logging
// Structured logging with Pino
import { LoggerModule } from 'nestjs-pino';
@Module({
imports: [
LoggerModule.forRoot({
pinoHttp: {
level: process.env.LOG_LEVEL || 'info',
transport: process.env.NODE_ENV !== 'production'
? { target: 'pino-pretty' }
: undefined,
redact: ['req.headers.authorization', 'req.body.password'],
},
}),
],
})
export class AppModule {}
Monitoring Metrics
| Metric |
Alert Threshold |
| Request latency p99 |
> 500ms |
| Error rate (5xx) |
> 1% |
| Memory usage |
> 80% |
| CPU usage |
> 70% |
| Active connections |
> 1000 |
| Request queue depth |
> 100 |
Exception Handling
// Global exception filter
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
constructor(private readonly logger: Logger) {}
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const request = ctx.getRequest();
const status = exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const message = exception instanceof HttpException
? exception.getResponse()
: 'Internal server error';
this.logger.error({
statusCode: status,
path: request.url,
method: request.method,
message,
stack: exception instanceof Error ? exception.stack : undefined,
});
response.status(status).json({
statusCode: status,
message: status === 500 ? 'Internal server error' : message,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}
Checklist
When NOT to Use This Skill
- Minimalist APIs: Use Express for lightweight, unopinionated APIs
- Maximum Performance: Use Fastify for high-throughput, low-latency requirements
- Edge Runtimes: Use Hono for Cloudflare Workers, Vercel Edge, or Deno Deploy
- Microservices Communication: Defer to
kafka-expert or rabbitmq-expert for message brokers
- Database Operations: Use
prisma-expert or sql-expert for ORM/database specifics
- WebSocket Implementation: Use dedicated WebSocket skill (coming soon)
Anti-Patterns
| Anti-Pattern |
Why It's Bad |
Correct Approach |
Using console.log() for logging |
No structured logging, hard to query |
Use nestjs-pino or Winston with structured logs |
| Circular dependencies between modules |
Causes initialization failures |
Use forwardRef() or redesign module boundaries |
| Business logic in controllers |
Violates SRP, hard to test |
Move logic to services, controllers orchestrate only |
| Not using DTOs for validation |
Security risk, inconsistent data |
Use class-validator with DTOs for all inputs |
| Hardcoding config values |
Not portable, security risk |
Use @nestjs/config with env variables |
| Not implementing graceful shutdown |
Data loss, incomplete requests |
Handle SIGTERM, close connections properly |
| Mixing ORM logic with business logic |
Tight coupling, hard to test |
Use repository pattern, inject repositories |
| Not using guards for authorization |
Security vulnerabilities |
Implement guards for auth/authz checks |
Quick Troubleshooting
| Issue |
Likely Cause |
Solution |
| "Circular dependency detected" |
Module A imports B, B imports A |
Use forwardRef() or extract shared logic |
| "Cannot find module" in tests |
Path mapping not resolved |
Configure moduleNameMapper in Jest config |
| Guards not executing |
Wrong order in app setup |
Apply guards after pipes: app.useGlobalGuards() |
| DTOs not validating |
ValidationPipe not global |
Add app.useGlobalPipes(new ValidationPipe()) in main.ts |
| High memory usage |
Memory leaks in subscriptions |
Use takeUntil() or unsubscribe in onModuleDestroy() |
| Slow startup time |
Too many providers/imports |
Lazy load modules, optimize dependency tree |
| 404 for all routes |
Controllers not registered |
Add controllers to module's controllers array |
| Middleware not executing |
Incorrect order or path |
Check middleware order, use forRoutes('*') for global |
Reference Documentation
- Module Structure
- Guards & Pipes
- Deep: Architecture
1---2name: nestjs3description: |4 NestJS enterprise Node.js framework. Covers modules, controllers,5 services, guards, and dependency injection. Use when building6 scalable Node.js applications.78 USE WHEN: user mentions "NestJS", "nest", "@nestjs", "@Module", "@Controller", "@Injectable", asks about "dependency injection in Node.js", "enterprise Node.js framework", "TypeScript backend framework", "decorators in backend", "guards and pipes", "modular Node.js architecture"910 DO NOT USE FOR: Express (minimalist framework) - use `express` instead, Fastify (performance-focused) - use `fastify` instead, Hono (edge runtimes) - use `hono` instead, Deno frameworks - use `oak` or `fresh` instead11allowed-tools: Read, Grep, Glob, Write, Edit12metadata:13 source: https://skillmd.com/skills/claude-dev-suite/nestjs14---1516# NestJS Core Knowledge1718> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `nestjs` for comprehensive documentation.1920## Module Structure2122```ts23// users.module.ts24@Module({25 imports: [TypeOrmModule.forFeature([User])],26 controllers: [UsersController],27 providers: [UsersService],28 exports: [UsersService],29})30export class UsersModule {}31```3233## Controller3435```ts36@Controller('users')37export class UsersController {38 constructor(private readonly usersService: UsersService) {}3940 @Get()41 findAll(): Promise<User[]> {42 return this.usersService.findAll();43 }4445 @Get(':id')46 findOne(@Param('id') id: string): Promise<User> {47 return this.usersService.findOne(id);48 }4950 @Post()51 @HttpCode(201)52 create(@Body() createUserDto: CreateUserDto): Promise<User> {53 return this.usersService.create(createUserDto);54 }5556 @Put(':id')57 update(@Param('id') id: string, @Body() dto: UpdateUserDto) {58 return this.usersService.update(id, dto);59 }6061 @Delete(':id')62 @HttpCode(204)63 remove(@Param('id') id: string) {64 return this.usersService.remove(id);65 }66}67```6869## Service7071```ts72@Injectable()73export class UsersService {74 constructor(75 @InjectRepository(User)76 private usersRepository: Repository<User>,77 ) {}7879 findAll(): Promise<User[]> {80 return this.usersRepository.find();81 }8283 findOne(id: string): Promise<User | null> {84 return this.usersRepository.findOneBy({ id });85 }86}87```8889## Key Decorators9091| Decorator | Purpose |92|-----------|---------|93| `@Module` | Define module |94| `@Controller` | Define controller |95| `@Injectable` | Mark as provider |96| `@Get/@Post/@Put/@Delete` | HTTP methods |97| `@Body/@Param/@Query` | Request data |98| `@UseGuards` | Apply guards |99| `@UsePipes` | Apply pipes |100101## Production Readiness102103### Security Configuration104105```ts106// main.ts - Security setup107import { NestFactory } from '@nestjs/core';108import { ValidationPipe } from '@nestjs/common';109import helmet from 'helmet';110import * as compression from 'compression';111112async function bootstrap() {113 const app = await NestFactory.create(AppModule);114115 // Security headers116 app.use(helmet());117118 // CORS configuration119 app.enableCors({120 origin: process.env.ALLOWED_ORIGINS?.split(',') || [],121 credentials: true,122 });123124 // Global validation pipe125 app.useGlobalPipes(new ValidationPipe({126 whitelist: true, // Strip non-whitelisted properties127 forbidNonWhitelisted: true, // Throw on non-whitelisted128 transform: true, // Auto-transform payloads129 }));130131 // Response compression132 app.use(compression());133134 // Rate limiting (with @nestjs/throttler)135 // Configured in AppModule136137 await app.listen(process.env.PORT || 3000);138}139```140141```ts142// Rate limiting module143import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler';144import { APP_GUARD } from '@nestjs/core';145146@Module({147 imports: [148 ThrottlerModule.forRoot([{149 ttl: 60000, // 1 minute150 limit: 100, // 100 requests per minute151 }]),152 ],153 providers: [{154 provide: APP_GUARD,155 useClass: ThrottlerGuard,156 }],157})158export class AppModule {}159```160161### Health Checks162163```ts164// health.controller.ts165import { Controller, Get } from '@nestjs/common';166import { HealthCheck, HealthCheckService, HttpHealthIndicator, TypeOrmHealthIndicator } from '@nestjs/terminus';167168@Controller('health')169export class HealthController {170 constructor(171 private health: HealthCheckService,172 private http: HttpHealthIndicator,173 private db: TypeOrmHealthIndicator,174 ) {}175176 @Get()177 @HealthCheck()178 check() {179 return this.health.check([180 () => this.db.pingCheck('database'),181 ]);182 }183184 @Get('ready')185 @HealthCheck()186 readiness() {187 return this.health.check([188 () => this.db.pingCheck('database'),189 () => this.http.pingCheck('external-api', 'https://api.example.com/health'),190 ]);191 }192}193```194195### Logging196197```ts198// Structured logging with Pino199import { LoggerModule } from 'nestjs-pino';200201@Module({202 imports: [203 LoggerModule.forRoot({204 pinoHttp: {205 level: process.env.LOG_LEVEL || 'info',206 transport: process.env.NODE_ENV !== 'production'207 ? { target: 'pino-pretty' }208 : undefined,209 redact: ['req.headers.authorization', 'req.body.password'],210 },211 }),212 ],213})214export class AppModule {}215```216217### Monitoring Metrics218219| Metric | Alert Threshold |220|--------|-----------------|221| Request latency p99 | > 500ms |222| Error rate (5xx) | > 1% |223| Memory usage | > 80% |224| CPU usage | > 70% |225| Active connections | > 1000 |226| Request queue depth | > 100 |227228### Exception Handling229230```ts231// Global exception filter232@Catch()233export class AllExceptionsFilter implements ExceptionFilter {234 constructor(private readonly logger: Logger) {}235236 catch(exception: unknown, host: ArgumentsHost) {237 const ctx = host.switchToHttp();238 const response = ctx.getResponse();239 const request = ctx.getRequest();240241 const status = exception instanceof HttpException242 ? exception.getStatus()243 : HttpStatus.INTERNAL_SERVER_ERROR;244245 const message = exception instanceof HttpException246 ? exception.getResponse()247 : 'Internal server error';248249 this.logger.error({250 statusCode: status,251 path: request.url,252 method: request.method,253 message,254 stack: exception instanceof Error ? exception.stack : undefined,255 });256257 response.status(status).json({258 statusCode: status,259 message: status === 500 ? 'Internal server error' : message,260 timestamp: new Date().toISOString(),261 path: request.url,262 });263 }264}265```266267### Checklist268269- [ ] Helmet security headers enabled270- [ ] CORS properly configured271- [ ] Rate limiting implemented272- [ ] Input validation with class-validator273- [ ] Global exception filter274- [ ] Health/readiness endpoints275- [ ] Structured logging (no console.log)276- [ ] Secrets via environment variables277- [ ] HTTPS in production278- [ ] Request timeout configured279- [ ] Graceful shutdown handling280281## When NOT to Use This Skill282283- **Minimalist APIs**: Use Express for lightweight, unopinionated APIs284- **Maximum Performance**: Use Fastify for high-throughput, low-latency requirements285- **Edge Runtimes**: Use Hono for Cloudflare Workers, Vercel Edge, or Deno Deploy286- **Microservices Communication**: Defer to `kafka-expert` or `rabbitmq-expert` for message brokers287- **Database Operations**: Use `prisma-expert` or `sql-expert` for ORM/database specifics288- **WebSocket Implementation**: Use dedicated WebSocket skill (coming soon)289290## Anti-Patterns291292| Anti-Pattern | Why It's Bad | Correct Approach |293|--------------|--------------|------------------|294| Using `console.log()` for logging | No structured logging, hard to query | Use `nestjs-pino` or Winston with structured logs |295| Circular dependencies between modules | Causes initialization failures | Use `forwardRef()` or redesign module boundaries |296| Business logic in controllers | Violates SRP, hard to test | Move logic to services, controllers orchestrate only |297| Not using DTOs for validation | Security risk, inconsistent data | Use `class-validator` with DTOs for all inputs |298| Hardcoding config values | Not portable, security risk | Use `@nestjs/config` with env variables |299| Not implementing graceful shutdown | Data loss, incomplete requests | Handle `SIGTERM`, close connections properly |300| Mixing ORM logic with business logic | Tight coupling, hard to test | Use repository pattern, inject repositories |301| Not using guards for authorization | Security vulnerabilities | Implement guards for auth/authz checks |302303## Quick Troubleshooting304305| Issue | Likely Cause | Solution |306|-------|--------------|----------|307| "Circular dependency detected" | Module A imports B, B imports A | Use `forwardRef()` or extract shared logic |308| "Cannot find module" in tests | Path mapping not resolved | Configure `moduleNameMapper` in Jest config |309| Guards not executing | Wrong order in app setup | Apply guards after pipes: `app.useGlobalGuards()` |310| DTOs not validating | ValidationPipe not global | Add `app.useGlobalPipes(new ValidationPipe())` in main.ts |311| High memory usage | Memory leaks in subscriptions | Use `takeUntil()` or unsubscribe in `onModuleDestroy()` |312| Slow startup time | Too many providers/imports | Lazy load modules, optimize dependency tree |313| 404 for all routes | Controllers not registered | Add controllers to module's `controllers` array |314| Middleware not executing | Incorrect order or path | Check middleware order, use `forRoutes('*')` for global |315316## Reference Documentation317- [Module Structure](quick-ref/modules.md)318- [Guards & Pipes](quick-ref/guards.md)319- [Deep: Architecture](deep-docs/architecture/)