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: MIT5metadata:6 source: https://skillmd.com/skills/jeffallan/nestjs-expert7 author: https://github.com/Jeffallan8 version: "1.1.0"9 domain: backend10 triggers: NestJS, Nest, Node.js backend, TypeScript backend, dependency injection, controller, service, module, guard, interceptor11 role: specialist12 scope: implementation13 output-format: code14 related-skills: fullstack-guardian, test-master, devops-engineer15---1617# NestJS Expert1819Senior NestJS specialist with deep expertise in enterprise-grade, scalable TypeScript backend applications.2021## Core Workflow22231. **Analyze requirements** — Identify modules, endpoints, entities, and relationships242. **Design structure** — Plan module organization and inter-module dependencies253. **Implement** — Create modules, services, and controllers with proper DI wiring264. **Secure** — Add guards, validation pipes, and authentication275. **Verify** — Run `npm run lint`, `npm run test`, and confirm DI graph with `nest info`286. **Test** — Write unit tests for services and E2E tests for controllers2930## Reference Guide3132Load detailed guidance based on context:3334| Topic | Reference | Load When |35|-------|-----------|-----------|36| Controllers | `references/controllers-routing.md` | Creating controllers, routing, Swagger docs |37| Services | `references/services-di.md` | Services, dependency injection, providers |38| DTOs | `references/dtos-validation.md` | Validation, class-validator, DTOs |39| Authentication | `references/authentication.md` | JWT, Passport, guards, authorization |40| Testing | `references/testing-patterns.md` | Unit tests, E2E tests, mocking |41| Express Migration | `references/migration-from-express.md` | Migrating from Express.js to NestJS |4243## Code Examples4445### Controller with DTO Validation and Swagger4647```typescript48// create-user.dto.ts49import { IsEmail, IsString, MinLength } from 'class-validator';50import { ApiProperty } from '@nestjs/swagger';5152export class CreateUserDto {53 @ApiProperty({ example: 'user@example.com' })54 @IsEmail()55 email: string;5657 @ApiProperty({ example: 'strongPassword123', minLength: 8 })58 @IsString()59 @MinLength(8)60 password: string;61}6263// users.controller.ts64import { Body, Controller, Post, HttpCode, HttpStatus } from '@nestjs/common';65import { ApiCreatedResponse, ApiTags } from '@nestjs/swagger';66import { UsersService } from './users.service';67import { CreateUserDto } from './dto/create-user.dto';6869@ApiTags('users')70@Controller('users')71export class UsersController {72 constructor(private readonly usersService: UsersService) {}7374 @Post()75 @HttpCode(HttpStatus.CREATED)76 @ApiCreatedResponse({ description: 'User created successfully.' })77 create(@Body() createUserDto: CreateUserDto) {78 return this.usersService.create(createUserDto);79 }80}81```8283### Service with Dependency Injection and Error Handling8485```typescript86// users.service.ts87import { Injectable, ConflictException, NotFoundException } from '@nestjs/common';88import { InjectRepository } from '@nestjs/typeorm';89import { Repository } from 'typeorm';90import { User } from './entities/user.entity';91import { CreateUserDto } from './dto/create-user.dto';9293@Injectable()94export class UsersService {95 constructor(96 @InjectRepository(User)97 private readonly usersRepository: Repository<User>,98 ) {}99100 async create(createUserDto: CreateUserDto): Promise<User> {101 const existing = await this.usersRepository.findOneBy({ email: createUserDto.email });102 if (existing) {103 throw new ConflictException('Email already registered');104 }105 const user = this.usersRepository.create(createUserDto);106 return this.usersRepository.save(user);107 }108109 async findOne(id: number): Promise<User> {110 const user = await this.usersRepository.findOneBy({ id });111 if (!user) {112 throw new NotFoundException(`User #${id} not found`);113 }114 return user;115 }116}117```118119### Module Definition120121```typescript122// users.module.ts123import { Module } from '@nestjs/common';124import { TypeOrmModule } from '@nestjs/typeorm';125import { UsersController } from './users.controller';126import { UsersService } from './users.service';127import { User } from './entities/user.entity';128129@Module({130 imports: [TypeOrmModule.forFeature([User])],131 controllers: [UsersController],132 providers: [UsersService],133 exports: [UsersService], // export only when other modules need this service134})135export class UsersModule {}136```137138### Unit Test for Service139140```typescript141// users.service.spec.ts142import { Test, TestingModule } from '@nestjs/testing';143import { getRepositoryToken } from '@nestjs/typeorm';144import { ConflictException } from '@nestjs/common';145import { UsersService } from './users.service';146import { User } from './entities/user.entity';147148const mockRepo = {149 findOneBy: jest.fn(),150 create: jest.fn(),151 save: jest.fn(),152};153154describe('UsersService', () => {155 let service: UsersService;156157 beforeEach(async () => {158 const module: TestingModule = await Test.createTestingModule({159 providers: [160 UsersService,161 { provide: getRepositoryToken(User), useValue: mockRepo },162 ],163 }).compile();164 service = module.get<UsersService>(UsersService);165 jest.clearAllMocks();166 });167168 it('throws ConflictException when email already exists', async () => {169 mockRepo.findOneBy.mockResolvedValue({ id: 1, email: 'user@example.com' });170 await expect(171 service.create({ email: 'user@example.com', password: 'pass1234' }),172 ).rejects.toThrow(ConflictException);173 });174});175```176177## Constraints178179### MUST DO180- Use `@Injectable()` and constructor injection for all services — never instantiate services with `new`181- Validate all inputs with `class-validator` decorators on DTOs and enable `ValidationPipe` globally182- Use DTOs for all request/response bodies; never pass raw `req.body` to services183- Throw typed HTTP exceptions (`NotFoundException`, `ConflictException`, etc.) in services184- Document all endpoints with `@ApiTags`, `@ApiOperation`, and response decorators185- Write unit tests for every service method using `Test.createTestingModule`186- Store all config values via `ConfigModule` and `process.env`; never hardcode them187188### MUST NOT DO189- Expose passwords, secrets, or internal stack traces in responses190- Accept unvalidated user input — always apply `ValidationPipe`191- Use `any` type unless absolutely necessary and documented192- Create circular dependencies between modules — use `forwardRef()` only as a last resort193- Hardcode hostnames, ports, or credentials in source files194- Skip error handling in service methods195196## Output Templates197198When implementing a NestJS feature, provide in this order:1991. Module definition (`.module.ts`)2002. Controller with Swagger decorators (`.controller.ts`)2013. Service with typed error handling (`.service.ts`)2024. DTOs with `class-validator` decorators (`dto/*.dto.ts`)2035. Unit tests for service methods (`*.service.spec.ts`)204205## Knowledge Reference206207NestJS, TypeScript, TypeORM, Prisma, Passport, JWT, class-validator, class-transformer, Swagger/OpenAPI, Jest, Supertest, Guards, Interceptors, Pipes, Filters208209[Documentation](https://jeffallan.github.io/claude-skills/skills/backend/nestjs-expert/)