affaan-m/ECC

nestjs-patterns

NestJS architecture patterns for modules, controllers, providers, DTO validation, guards, interceptors, config, and production-grade TypeScript backends.

79CollectingNetwork access
See how to use itView GitHub source
npx skills add https://github.com/affaan-m/ECC --skill ".kiro/skills/nestjs-patterns"
Automated source guide

Source checked Jul 28, 2026·Refresh due Oct 26, 2026

Reorganized from the pinned upstream SKILL.md

Turn nestjs-patterns's source instructions into a guide you can follow

According to the pinned SKILL.md from affaan-m/ECC: Production-grade NestJS patterns for modular TypeScript backends.

npx skills add https://github.com/affaan-m/ECC --skill ".kiro/skills/nestjs-patterns"
Check the pinned source

Best fit

  • NestJS architecture patterns for modules, controllers, providers, DTO validation, guards, interceptors, config, and production-grade TypeScript backends.

Bring this context

  • Keep auth strategies and guards module-local unless they are truly shared.
  • Encode coarse access rules in guards, then do resource-specific authorization in services.
  • Prefer explicit request types for authenticated request objects.

Expected outputs

  • A result that follows the pinned nestjs-patterns instructions.
  • A concise record of assumptions, inputs used, and unresolved questions.
  • A final check against the source workflow and relevant permission signals.

Key source sections

Read nestjs-patterns through these 5 source sections

Sections are extracted automatically from the pinned SKILL.md and link back to the source.

01

When to Activate

Building NestJS APIs or services

SKILL.md · When to Activate
Building NestJS APIs or servicesStructuring modules, controllers, and providersAdding DTO validation, guards, interceptors, or exception filters
02

Project Structure

Keep domain code inside feature modules.

SKILL.md · Project Structure
Keep domain code inside feature modules.Put cross-cutting filters, decorators, guards, and interceptors in common/.Keep DTOs close to the module that owns them.
03

Bootstrap and Global Validation

Always enable whitelist and forbidNonWhitelisted on public APIs.

SKILL.md · Bootstrap and Global Validation
Always enable whitelist and forbidNonWhitelisted on public APIs.Prefer one global validation pipe instead of repeating validation config per route.- Always enable whitelist and forbidNonWhitelisted on public APIs. - Prefer one global validation pipe instead of repeating validation config per route.
04

Modules, Controllers, and Providers

Controllers should stay thin: parse HTTP input, call a provider, return response DTOs.

SKILL.md · Modules, Controllers, and Providers
Controllers should stay thin: parse HTTP input, call a provider, return response DTOs.Put business logic in injectable services, not controllers.Export only the providers other modules genuinely need.
05

DTOs and Validation

Validate every request DTO with class-validator.

SKILL.md · DTOs and Validation
Validate every request DTO with class-validator.Use dedicated response DTOs or serializers instead of returning ORM entities directly.Avoid leaking internal fields such as password hashes, tokens, or audit columns.

SkillSignal prompt templates

Provide the task, context, and acceptance criteria

These prompts were written by SkillSignal from the source structure; they are not upstream text.

Task-start prompt

Confirm source fit, inputs, and outputs before acting.

Use nestjs-patterns to help me with: [specific task]. Context: [files, data, or background]. Constraints: [environment, scope, and prohibited actions]. Before acting, check the pinned SKILL.md and explain which sections apply, what inputs are still missing, and what you will deliver.

Source-guided execution

Make the Agent explicitly follow the key extracted sections.

Apply the pinned nestjs-patterns source to [task]. Pay particular attention to these source sections: “When to Activate”, “Project Structure”, “Bootstrap and Global Validation”, “Modules, Controllers, and Providers”, “DTOs and Validation”. Preserve the important decision at each step. Mark facts not covered by the source as “needs confirmation” instead of inventing them. Then verify the result against my acceptance criteria: [criteria].

Result-review prompt

Check omissions, permissions, and source drift before delivery.

Review the current nestjs-patterns result: (1) does it satisfy the original task; (2) were any applicable steps or limits in the pinned SKILL.md missed; (3) did it perform any unauthorized file, command, network, or data action; and (4) which conclusions remain unverified? List issues first, then fix only what the source or user authorization supports.

Output checklist

Verify each item before delivery

The task matches the purpose documented in the SKILL.md.

The source section “When to Activate” has been checked.

The source section “Project Structure” has been checked.

The source section “Bootstrap and Global Validation” has been checked.

The source section “Modules, Controllers, and Providers” has been checked.

Inputs, constraints, and acceptance criteria are explicit.

Unverified facts, compatibility, and outcome claims are clearly marked.

Any file, command, network, or data action has been reviewed.

Choose a different workflow

When another Skill is the better fit

FAQ

What does nestjs-patterns do?

Production-grade NestJS patterns for modular TypeScript backends.

How do I start using nestjs-patterns?

The catalog detected this source-specific install command: npx skills add https://github.com/affaan-m/ECC --skill ".kiro/skills/nestjs-patterns". Inspect the command and pinned source before running it.

Which Agent platforms does it declare?

No dedicated Agent platform is declared in the pinned source record.

Repository stars
234,327
Repository forks
35,711
Quality
79/100
Source repository last pushed

Quality breakdown

Based on traceable docs and repository signals; stars are not treated as quality.

79/100
Documentation25/30
Specificity14/25
Maintenance20/20
Trust signals20/25
View original Skill.mdThis page is parsed directly from the repository SKILL.md without editorial rewriting. Collected: Jul 28, 2026 · about 2 min

NestJS Development Patterns

Production-grade NestJS patterns for modular TypeScript backends.

When to Activate

  • Building NestJS APIs or services
  • Structuring modules, controllers, and providers
  • Adding DTO validation, guards, interceptors, or exception filters
  • Configuring environment-aware settings and database integrations
  • Testing NestJS units or HTTP endpoints

Project Structure

src/
├── app.module.ts
├── main.ts
├── common/
│   ├── filters/
│   ├── guards/
│   ├── interceptors/
│   └── pipes/
├── config/
│   ├── configuration.ts
│   └── validation.ts
├── modules/
│   ├── auth/
│   │   ├── auth.controller.ts
│   │   ├── auth.module.ts
│   │   ├── auth.service.ts
│   │   ├── dto/
│   │   ├── guards/
│   │   └── strategies/
│   └── users/
│       ├── dto/
│       ├── entities/
│       ├── users.controller.ts
│       ├── users.module.ts
│       └── users.service.ts
└── prisma/ or database/
  • Keep domain code inside feature modules.
  • Put cross-cutting filters, decorators, guards, and interceptors in common/.
  • Keep DTOs close to the module that owns them.

Bootstrap and Global Validation

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { bufferLogs: true });

  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
      transformOptions: { enableImplicitConversion: true },
    }),
  );

  app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));
  app.useGlobalFilters(new HttpExceptionFilter());

  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
  • Always enable whitelist and forbidNonWhitelisted on public APIs.
  • Prefer one global validation pipe instead of repeating validation config per route.

Modules, Controllers, and Providers

@Module({
  controllers: [UsersController],
  providers: [UsersService],
  exports: [UsersService],
})
export class UsersModule {}

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get(':id')
  getById(@Param('id', ParseUUIDPipe) id: string) {
    return this.usersService.getById(id);
  }

  @Post()
  create(@Body() dto: CreateUserDto) {
    return this.usersService.create(dto);
  }
}

@Injectable()
export class UsersService {
  constructor(private readonly usersRepo: UsersRepository) {}

  async create(dto: CreateUserDto) {
    return this.usersRepo.create(dto);
  }
}
  • Controllers should stay thin: parse HTTP input, call a provider, return response DTOs.
  • Put business logic in injectable services, not controllers.
  • Export only the providers other modules genuinely need.

DTOs and Validation

export class CreateUserDto {
  @IsEmail()
  email!: string;

  @IsString()
  @Length(2, 80)
  name!: string;

  @IsOptional()
  @IsEnum(UserRole)
  role?: UserRole;
}
  • Validate every request DTO with class-validator.
  • Use dedicated response DTOs or serializers instead of returning ORM entities directly.
  • Avoid leaking internal fields such as password hashes, tokens, or audit columns.

Auth, Guards, and Request Context

@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('admin')
@Get('admin/report')
getAdminReport(@Req() req: AuthenticatedRequest) {
  return this.reportService.getForUser(req.user.id);
}
  • Keep auth strategies and guards module-local unless they are truly shared.
  • Encode coarse access rules in guards, then do resource-specific authorization in services.
  • Prefer explicit request types for authenticated request objects.

Exception Filters and Error Shape

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger(HttpExceptionFilter.name);

  catch(exception: unknown, host: ArgumentsHost) {
    const response = host.switchToHttp().getResponse<Response>();
    const request = host.switchToHttp().getRequest<Request>();

    if (exception instanceof HttpException) {
      return response.status(exception.getStatus()).json({
        path: request.url,
        error: exception.getResponse(),
      });
    }

    this.logger.error(
      `Unhandled exception at ${request.url}: ${exception instanceof Error ? exception.message : exception}`,
      exception instanceof Error ? exception.stack : undefined,
    );

    return response.status(500).json({
      path: request.url,
      error: 'Internal server error',
    });
  }
}
  • Keep one consistent error envelope across the API.
  • Throw framework exceptions for expected client errors; log and wrap unexpected failures centrally.

Config and Environment Validation

ConfigModule.forRoot({
  isGlobal: true,
  load: [configuration],
  validate: validateEnv,
});
  • Validate env at boot, not lazily at first request.
  • Keep config access behind typed helpers or config services.
  • Split dev/staging/prod concerns in config factories instead of branching throughout feature code.

Persistence and Transactions

  • Keep repository / ORM code behind providers that speak domain language.
  • For Prisma or TypeORM, isolate transactional workflows in services that own the unit of work.
  • Do not let controllers coordinate multi-step writes directly.

Testing

describe('UsersController', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({
      imports: [UsersModule],
    }).compile();

    app = moduleRef.createNestApplication();
    app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
    await app.init();
  });
});
  • Unit test providers in isolation with mocked dependencies.
  • Add request-level tests for guards, validation pipes, and exception filters.
  • Reuse the same global pipes/filters in tests that you use in production.

Production Defaults

  • Enable structured logging and request correlation ids.
  • Terminate on invalid env/config instead of booting partially.
  • Prefer async provider initialization for DB/cache clients with explicit health checks.
  • Keep background jobs and event consumers in their own modules, not inside HTTP controllers.
  • Make rate limiting, auth, and audit logging explicit for public endpoints.
Source repo
affaan-m/ECC
Skill path
.kiro/skills/nestjs-patterns/SKILL.md
Commit SHA
4e973d3eaf92
Repository license
MIT
Data collected