Skip to main content
Agent skill

Nestjs Patterns

NestJS architecture patterns for modules, controllers, providers, DTO validation, guards, interceptors, config, and production-grade TypeScript backends. Use when building or reviewing a NestJS backend — modules, providers, DTO validation, guards, or interceptors.

Get started

Get the complete skill folder, including its scripts and reference files.

·

When to use this skill

Use Nestjs Patterns when an AI agent needs a reusable SKILL.md workflow for this job: NestJS architecture patterns for modules, controllers, providers, DTO validation, guards, interceptors, config, and production-grade TypeScript backends. Use when building or reviewing a NestJS backend — modules, providers, DTO validation, guards, or interceptors.

When not to use it

Skip Nestjs Patterns when the task is outside the coding category, or when a more specific skill in this directory already covers the same workflow with clearer triggers.

How to install

Where will you use it?

Install scope
Claude Code folder setup
mkdir -p ~/.claude/skills/nestjs-patterns
# Save SKILL.md to ~/.claude/skills/nestjs-patterns/SKILL.md
  1. Claude Code personal install: place the skill and its bundled files at ~/.claude/skills/nestjs-patterns/SKILL.md. For a shared project, commit the folder at .claude/skills/nestjs-patterns/ instead.
  2. Current Claude Code detects SKILL.md changes in watched directories during the session. If you just created a top-level skills directory, run /reload-skills. Check that the skill is listed before testing its trigger.
  3. For Claude chat or Cowork in the Desktop app, manage uploaded skills in Customize > Skills; copying files into a local Claude Code folder is not a Desktop install. Other agents may use different install locations.

Full install guide for Claude, Cursor, and Codex →

Try a starter prompt

After installing the skill, paste this starter prompt into your agent to verify it triggers on a small task.

Starter prompt
Use the Nestjs Patterns skill for this task: Use Nestjs Patterns when this documented workflow matches the task. Confirm any required inputs or files before making changes.

What supports this recommendation?

71/100 provisional content score. This measures documentation, practical detail and source signals. It is not a measured task success rate or a security certification.

Documentation
77/100
Practical detail
68/100
Source evidence
63/100
Source signals
72/100
Model compatibility evidence
  • claudeuntested

    No model-specific signal or recorded compatibility test was found.

  • chatgptuntested

    No model-specific signal or recorded compatibility test was found.

  • geminiuntested

    No model-specific signal or recorded compatibility test was found.

  • copilotuntested

    No model-specific signal or recorded compatibility test was found.

  • llamauntested

    No model-specific signal or recorded compatibility test was found.

  • perplexityuntested

    No model-specific signal or recorded compatibility test was found.

  • mistraluntested

    No model-specific signal or recorded compatibility test was found.

  • grokuntested

    No model-specific signal or recorded compatibility test was found.

Inferred compatibility is based on content signals. Check the app, its available tools and setup requirements before running a skill.

What this skill does

# 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

```text 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

```ts 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

```ts @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

```ts 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

```ts @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

```ts @Catch() export class HttpExceptionFilter implements ExceptionFilter { 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(), }); }

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

```ts 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

```ts 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.

Intended uses

  • Use Nestjs Patterns when this documented workflow matches the task.

Implementation notes

  • Review the source instructions and adapt inputs before running the workflow.

Try it, then tell us how it went

A copied prompt does not tell us whether the task worked. Report your result after checking the output. We collect your tool and outcome, never your files or prompt.