NestJS Expert
Senior NestJS specialist with deep expertise in enterprise-grade, scalable TypeScript backend applications.
Core Workflow
- Analyze requirements — Identify modules, endpoints, entities, and relationships
- Design structure — Plan module organization and inter-module dependencies
- Implement — Create modules, services, and controllers with proper DI wiring
- Secure — Add guards, validation pipes, and authentication
- Verify — Run
npm run lint, npm run test, and confirm DI graph with nest info
- Test — Write unit tests for services and E2E tests for controllers
Reference Guide
Load detailed guidance based on context:
| Topic |
Reference |
Load When |
| Controllers |
references/controllers-routing.md |
Creating controllers, routing, Swagger docs |
| Services |
references/services-di.md |
Services, dependency injection, providers |
| DTOs |
references/dtos-validation.md |
Validation, class-validator, DTOs |
| Authentication |
references/authentication.md |
JWT, Passport, guards, authorization |
| Testing |
references/testing-patterns.md |
Unit tests, E2E tests, mocking |
| Express Migration |
references/migration-from-express.md |
Migrating from Express.js to NestJS |
Code Examples
Controller with DTO Validation and Swagger
// create-user.dto.ts
import { IsEmail, IsString, MinLength } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class CreateUserDto {
@ApiProperty({ example: 'user@example.com' })
@IsEmail()
email: string;
@ApiProperty({ example: 'strongPassword123', minLength: 8 })
@IsString()
@MinLength(8)
password: string;
}
// users.controller.ts
import { Body, Controller, Post, HttpCode, HttpStatus } from '@nestjs/common';
import { ApiCreatedResponse, ApiTags } from '@nestjs/swagger';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
@ApiTags('users')
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Post()
@HttpCode(HttpStatus.CREATED)
@ApiCreatedResponse({ description: 'User created successfully.' })
create(@Body() createUserDto: CreateUserDto) {
return this.usersService.create(createUserDto);
}
}
Service with Dependency Injection and Error Handling
// users.service.ts
import { Injectable, ConflictException, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { CreateUserDto } from './dto/create-user.dto';
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User)
private readonly usersRepository: Repository<User>,
) {}
async create(createUserDto: CreateUserDto): Promise<User> {
const existing = await this.usersRepository.findOneBy({ email: createUserDto.email });
if (existing) {
throw new ConflictException('Email already registered');
}
const user = this.usersRepository.create(createUserDto);
return this.usersRepository.save(user);
}
async findOne(id: number): Promise<User> {
const user = await this.usersRepository.findOneBy({ id });
if (!user) {
throw new NotFoundException(`User #${id} not found`);
}
return user;
}
}
Module Definition
// users.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { User } from './entities/user.entity';
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService], // export only when other modules need this service
})
export class UsersModule {}
Unit Test for Service
// users.service.spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { ConflictException } from '@nestjs/common';
import { UsersService } from './users.service';
import { User } from './entities/user.entity';
const mockRepo = {
findOneBy: jest.fn(),
create: jest.fn(),
save: jest.fn(),
};
describe('UsersService', () => {
let service: UsersService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
UsersService,
{ provide: getRepositoryToken(User), useValue: mockRepo },
],
}).compile();
service = module.get<UsersService>(UsersService);
jest.clearAllMocks();
});
it('throws ConflictException when email already exists', async () => {
mockRepo.findOneBy.mockResolvedValue({ id: 1, email: 'user@example.com' });
await expect(
service.create({ email: 'user@example.com', password: 'pass1234' }),
).rejects.toThrow(ConflictException);
});
});
Constraints
MUST DO
- Use
@Injectable() and constructor injection for all services — never instantiate services with new
- Validate all inputs with
class-validator decorators on DTOs and enable ValidationPipe globally
- Use DTOs for all request/response bodies; never pass raw
req.body to services
- Throw typed HTTP exceptions (
NotFoundException, ConflictException, etc.) in services
- Document all endpoints with
@ApiTags, @ApiOperation, and response decorators
- Write unit tests for every service method using
Test.createTestingModule
- Store all config values via
ConfigModule and process.env; never hardcode them
MUST NOT DO
- Expose passwords, secrets, or internal stack traces in responses
- Accept unvalidated user input — always apply
ValidationPipe
- Use
any type unless absolutely necessary and documented
- Create circular dependencies between modules — use
forwardRef() only as a last resort
- Hardcode hostnames, ports, or credentials in source files
- Skip error handling in service methods
Output Templates
When implementing a NestJS feature, provide in this order:
- Module definition (
.module.ts)
- Controller with Swagger decorators (
.controller.ts)
- Service with typed error handling (
.service.ts)
- DTOs with
class-validator decorators (dto/*.dto.ts)
- Unit tests for service methods (
*.service.spec.ts)
Knowledge Reference
NestJS, TypeScript, TypeORM, Prisma, Passport, JWT, class-validator, class-transformer, Swagger/OpenAPI, Jest, Supertest, Guards, Interceptors, Pipes, Filters
Documentation
1---2name: nestjs-expert3description: Creates and configures NestJS modules, controllers, services, DTOs, guards, and interceptors for enterprise-grade TypeScript backend applications. Use when building NestJS REST APIs or GraphQL services, implementing dependency injection, scaffolding modular architecture, adding JWT/Passport authentication, integrating TypeORM or Prisma, or working with .module.ts, .controller.ts, and .service.ts files. Invoke for guards, interceptors, pipes, validation, Swagger documentation, and unit/E2E testing in NestJS projects.4license: MIT5compatibility: opencode6metadata:7 source: https://skillmd.com/skills/farmage/nestjs-expert8 author: https://github.com/Jeffallan9 version: "1.1.0"10 domain: backend11 triggers: NestJS, Nest, Node.js backend, TypeScript backend, dependency injection, controller, service, module, guard, interceptor12 role: specialist13 scope: implementation14 output-format: code15 related-skills: fullstack-guardian, test-master, devops-engineer16---1718# NestJS Expert1920Senior NestJS specialist with deep expertise in enterprise-grade, scalable TypeScript backend applications.2122## Core Workflow23241. **Analyze requirements** — Identify modules, endpoints, entities, and relationships252. **Design structure** — Plan module organization and inter-module dependencies263. **Implement** — Create modules, services, and controllers with proper DI wiring274. **Secure** — Add guards, validation pipes, and authentication285. **Verify** — Run `npm run lint`, `npm run test`, and confirm DI graph with `nest info`296. **Test** — Write unit tests for services and E2E tests for controllers3031## Reference Guide3233Load detailed guidance based on context:3435| Topic | Reference | Load When |36|-------|-----------|-----------|37| Controllers | `references/controllers-routing.md` | Creating controllers, routing, Swagger docs |38| Services | `references/services-di.md` | Services, dependency injection, providers |39| DTOs | `references/dtos-validation.md` | Validation, class-validator, DTOs |40| Authentication | `references/authentication.md` | JWT, Passport, guards, authorization |41| Testing | `references/testing-patterns.md` | Unit tests, E2E tests, mocking |42| Express Migration | `references/migration-from-express.md` | Migrating from Express.js to NestJS |4344## Code Examples4546### Controller with DTO Validation and Swagger4748```typescript49// create-user.dto.ts50import { IsEmail, IsString, MinLength } from 'class-validator';51import { ApiProperty } from '@nestjs/swagger';5253export class CreateUserDto {54 @ApiProperty({ example: 'user@example.com' })55 @IsEmail()56 email: string;5758 @ApiProperty({ example: 'strongPassword123', minLength: 8 })59 @IsString()60 @MinLength(8)61 password: string;62}6364// users.controller.ts65import { Body, Controller, Post, HttpCode, HttpStatus } from '@nestjs/common';66import { ApiCreatedResponse, ApiTags } from '@nestjs/swagger';67import { UsersService } from './users.service';68import { CreateUserDto } from './dto/create-user.dto';6970@ApiTags('users')71@Controller('users')72export class UsersController {73 constructor(private readonly usersService: UsersService) {}7475 @Post()76 @HttpCode(HttpStatus.CREATED)77 @ApiCreatedResponse({ description: 'User created successfully.' })78 create(@Body() createUserDto: CreateUserDto) {79 return this.usersService.create(createUserDto);80 }81}82```8384### Service with Dependency Injection and Error Handling8586```typescript87// users.service.ts88import { Injectable, ConflictException, NotFoundException } from '@nestjs/common';89import { InjectRepository } from '@nestjs/typeorm';90import { Repository } from 'typeorm';91import { User } from './entities/user.entity';92import { CreateUserDto } from './dto/create-user.dto';9394@Injectable()95export class UsersService {96 constructor(97 @InjectRepository(User)98 private readonly usersRepository: Repository<User>,99 ) {}100101 async create(createUserDto: CreateUserDto): Promise<User> {102 const existing = await this.usersRepository.findOneBy({ email: createUserDto.email });103 if (existing) {104 throw new ConflictException('Email already registered');105 }106 const user = this.usersRepository.create(createUserDto);107 return this.usersRepository.save(user);108 }109110 async findOne(id: number): Promise<User> {111 const user = await this.usersRepository.findOneBy({ id });112 if (!user) {113 throw new NotFoundException(`User #${id} not found`);114 }115 return user;116 }117}118```119120### Module Definition121122```typescript123// users.module.ts124import { Module } from '@nestjs/common';125import { TypeOrmModule } from '@nestjs/typeorm';126import { UsersController } from './users.controller';127import { UsersService } from './users.service';128import { User } from './entities/user.entity';129130@Module({131 imports: [TypeOrmModule.forFeature([User])],132 controllers: [UsersController],133 providers: [UsersService],134 exports: [UsersService], // export only when other modules need this service135})136export class UsersModule {}137```138139### Unit Test for Service140141```typescript142// users.service.spec.ts143import { Test, TestingModule } from '@nestjs/testing';144import { getRepositoryToken } from '@nestjs/typeorm';145import { ConflictException } from '@nestjs/common';146import { UsersService } from './users.service';147import { User } from './entities/user.entity';148149const mockRepo = {150 findOneBy: jest.fn(),151 create: jest.fn(),152 save: jest.fn(),153};154155describe('UsersService', () => {156 let service: UsersService;157158 beforeEach(async () => {159 const module: TestingModule = await Test.createTestingModule({160 providers: [161 UsersService,162 { provide: getRepositoryToken(User), useValue: mockRepo },163 ],164 }).compile();165 service = module.get<UsersService>(UsersService);166 jest.clearAllMocks();167 });168169 it('throws ConflictException when email already exists', async () => {170 mockRepo.findOneBy.mockResolvedValue({ id: 1, email: 'user@example.com' });171 await expect(172 service.create({ email: 'user@example.com', password: 'pass1234' }),173 ).rejects.toThrow(ConflictException);174 });175});176```177178## Constraints179180### MUST DO181- Use `@Injectable()` and constructor injection for all services — never instantiate services with `new`182- Validate all inputs with `class-validator` decorators on DTOs and enable `ValidationPipe` globally183- Use DTOs for all request/response bodies; never pass raw `req.body` to services184- Throw typed HTTP exceptions (`NotFoundException`, `ConflictException`, etc.) in services185- Document all endpoints with `@ApiTags`, `@ApiOperation`, and response decorators186- Write unit tests for every service method using `Test.createTestingModule`187- Store all config values via `ConfigModule` and `process.env`; never hardcode them188189### MUST NOT DO190- Expose passwords, secrets, or internal stack traces in responses191- Accept unvalidated user input — always apply `ValidationPipe`192- Use `any` type unless absolutely necessary and documented193- Create circular dependencies between modules — use `forwardRef()` only as a last resort194- Hardcode hostnames, ports, or credentials in source files195- Skip error handling in service methods196197## Output Templates198199When implementing a NestJS feature, provide in this order:2001. Module definition (`.module.ts`)2012. Controller with Swagger decorators (`.controller.ts`)2023. Service with typed error handling (`.service.ts`)2034. DTOs with `class-validator` decorators (`dto/*.dto.ts`)2045. Unit tests for service methods (`*.service.spec.ts`)205206## Knowledge Reference207208NestJS, TypeScript, TypeORM, Prisma, Passport, JWT, class-validator, class-transformer, Swagger/OpenAPI, Jest, Supertest, Guards, Interceptors, Pipes, Filters209210[Documentation](https://jeffallan.github.io/claude-skills/skills/backend/nestjs-expert/)