debug:nestjs
Debug NestJS issues systematically. Use when encountering dependency injection errors like "Nest can't resolve dependencies", module import issues, circular dependencies between services or modules, guard and interceptor problems, decorator configuration issues, microservice communication errors, WebSocket gateway failures, pipe validation errors, or any NestJS-specific runtime issues requiring diagnosis.
What this skill does
# NestJS Debugging Guide
This guide provides a systematic approach to debugging NestJS applications. Use the four-phase methodology below to efficiently identify and resolve issues.
## Common Error Patterns
### 1. Dependency Resolution Errors
**Error Message:**
```
Nest can't resolve dependencies of the <ProviderName> (?). Please make sure that the argument <DependencyName> at index [0] is available in the <ModuleName> context.
```
**Common Causes:**
- Provider not added to module's `providers` array
- Missing `@Injectable()` decorator on service class
- Incorrect import/export between modules
- Typo in injection token name
- Missing `forRoot()`/`forRootAsync()` configuration
**Solutions:**
```typescript
// Ensure provider is in the module
@Module({
providers: [MyService], // Add missing provider here
exports: [MyService], // Export if used by other modules
})
export class MyModule {}
// Ensure @Injectable() decorator exists
@Injectable()
export class MyService {
constructor(private readonly dependency: OtherService) {}
}
// For external modules, import the module not just the service
@Module({
imports: [OtherModule], // Import the module
})
export class MyModule {}
```
### 2. Circular Dependency Errors
**Error Message:**
```
Nest cannot create the module instance. The module at index [X] of the imports array is undefined.
```
**Common Causes:**
- Two modules importing each other
- Two services depending on each other
- File-level circular imports (constants, types)
**Solutions:**
```typescript
// Use forwardRef() for circular module dependencies
@Module({
imports: [forwardRef(() => OtherModule)],
})
export class MyModule {}
// Use forwardRef() for circular service dependencies
@Injectable()
export class ServiceA {
constructor(
@Inject(forwardRef(() => ServiceB))
private serviceB: ServiceB,
) {}
}
// Alternative: Extract shared logic to a third module
@Module({
providers: [SharedService],
exports: [SharedService],
})
export class SharedModule {}
```
### 3. Guard/Interceptor Issues
**Error Message:**
```
Cannot read property 'canActivate' of undefined
Cannot read property 'intercept' of undefined
```
**Common Causes:**
- Guard/Interceptor not properly registered
- Missing `@UseGuards()` or `@UseInterceptors()` decorator
- Incorrect scope (request-scoped vs singleton)
- Dependencies not available in guard/interceptor context
**Solutions:**
```typescript
// Register globally in main.ts
app.useGlobalGuards(new AuthGuard());
app.useGlobalInterceptors(new LoggingInterceptor());
// Or register via module for DI support
@Module({
providers: [
{
provide: APP_GUARD,
useClass: AuthGuard,
},
{
provide: APP_INTERCEPTOR,
useClass: LoggingInterceptor,
},
],
})
export class AppModule {}
// Controller-level registration
@UseGuards(AuthGuard)
@UseInterceptors(LoggingInterceptor)
@Controller('users')
export class UsersController {}
```
### 4. Pipe Validation Errors
**Error Message:**
```
An instance of an invalid class-validator value was provided
Validation failed (expected type)
```
**Common Causes:**
- Missing `class-transformer` or `class-validator` packages
- DTO not properly decorated with validation decorators
- ValidationPipe not configured correctly
- Transform option not enabled
**Solutions:**
```typescript
// Enable ValidationPipe globally with proper options
app.useGlobalPipes(
new ValidationPipe({
whitelist: true, // Strip non-whitelisted properties
forbidNonWhitelisted: true, // Throw on extra properties
transform: true, // Auto-transform payloads to DTO instances
transformOptions: {
enableImplicitConversion: true,
},
}),
);
// Properly decorate DTOs
import { IsString, IsInt, Min, IsOptional } from 'class-validator';
import { Type } from 'class-transformer';
export class CreateUserDto {
@IsString()
name: string;
@IsInt()
@Min(0)
@Type(() => Number)
age: number;
@IsOptional()
@IsString()
email?: string;
}
```
### 5. Microservice Communication Errors
**Error Message:**
```
There is no matching message handler defined in the remote service
Connection refused / ECONNREFUSED
```
**Common Causes:**
- Message pattern mismatch between client and server
- Transport configuration mismatch
- Service not connected or not running
- Serialization/deserialization issues
**Solutions:**
```typescript
// Ensure matching patterns
// Server side
@MessagePattern({ cmd: 'get_user' })
async getUser(data: { id: number }) {
return this.usersService.findOne(data.id);
}
// Client side - pattern must match exactly
const user = await this.client.send({ cmd: 'get_user' }, { id: 1 }).toPromise();
// Check transport configuration matches
// Server
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
AppModule,
{
transport: Transport.TCP,
options: { host: '0.0.0.0', port: 3001 },
},
);
// Client module
ClientsModule.register([
{
name: 'USER_SERVICE',
transport: Transport.TCP,
options: { host: 'localhost', port: 3001 },
},
]);
```
### 6. WebSocket/Gateway Errors
**Error Message:**
```
Gateway is not defined
WebSocket connection failed
```
**Common Causes:**
- Missing `@WebSocketGateway()` decorator
- Gateway not added to module providers
- CORS issues with WebSocket connections
- Adapter not properly configured
**Solutions:**
```typescript
// Properly configure gateway
@WebSocketGateway({
cors: {
origin: '*',
},
namespace: '/events',
})
export class EventsGateway implements OnGatewayConnection {
@WebSocketServer()
server: Server;
handleConnection(client: Socket) {
console.log('Client connected:', client.id);
}
@SubscribeMessage('message')
handleMessage(client: Socket, payload: any): string {
return 'Hello world!';
}
}
// Add to module
@Module({
providers: [EventsGateway],
})
export class EventsModule {}
// Configure adapter in main.ts if needed
import { IoAdapter } from '@nestjs/platform-socket.io';
app.useWebSocketAdapter(new IoAdapter(app));
```
## Debugging Tools
### 1. NestJS Debug Mode
```bash
# Start with debug flag
nest start --debug --watch
# Or add to package.json
"start:debug": "nest start --debug --watch"
```
### 2. VS Code Debugger Configuration
Create `.vscode/launch.json`:
```json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug NestJS",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "start:debug"],
"console": "integratedTerminal",
"restart": true,
"autoAttachChildProcesses": true,
"sourceMaps": true,
"envFile": "${workspaceFolder}/.env"
},
{
"type": "node",
"request": "attach",
"name": "Attach to NestJS",
"port": 9229,
"restart": true,
"sourceMaps": true
}
]
}
```
### 3. Docker Debug Configuration
```yaml
# docker-compose.debug.yml
version: '3.8'
services:
api:
command: npm run start:debug
ports:
- "3000:3000"
- "9229:9229" # Debug port
environment:
- NODE_OPTIONS=--inspect=0.0.0.0:9229
```
### 4. Built-in Logger Service
```typescript
import { Logger, Injectable } from '@nestjs/common';
@Injectable()
export class MyService {
private readonly logger = new Logger(MyService.name);
async doSomething() {
this.logger.log('Processing started');
this.logger.debug('Debug info', { data: someData });
this.logger.warn('Warning message');
this.logger.error('Error occurred', error.stack);
this.logger.verbose('Verbose details');
}
}
// Configure logger level in main.ts
const app = await NestFactory.create(AppModule, {
logger: ['error', 'warn', 'log', 'debug', 'verbose'],
});
```
### 5. @nestjs/testing Utilities
```typescript
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
describe('UsersCRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.