---
name: nestjs-best-practices
description: "NestJS 11+ best practices for enterprise Node.js applications with TypeScript. Use when writing, reviewing, or refactoring NestJS controllers, services, modules, or APIs. Triggers on: NestJS modules, controllers, providers, dependency injection, @Injectable, @Controller, @Module, middleware, guards, interceptors, pipes, exception filters, ValidationPipe, class-validator, class-transformer, DTOs, JWT authentication, Passport strategies, @nestjs/passport, TypeORM entities, Prisma client, Drizzle ORM, repository pattern, circular dependencies, forwardRef, @nestjs/swagger, OpenAPI decorators, GraphQL resolvers, @nestjs/graphql, microservices, TCP transport, Redis transport, NATS, Kafka, NestJS 11 breaking changes, Express v5 migration, custom decorators, ConfigService, @nestjs/config, health checks, or NestJS testing patterns."
license: MIT
metadata:
  author: ejirocodes
  version: '1.0.0'
title: nestjs-best-practices
canonical_url: https://skilld.dev/gh/ejirocodes/agent-skills/nestjs-best-practices
last_updated: 2026-10-08T14:03:56.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [references/authentication.md](https://skilld.dev/api/skills-raw/ejirocodes/agent-skills/nestjs-best-practices/references/authentication.md), [references/core-architecture.md](https://skilld.dev/api/skills-raw/ejirocodes/agent-skills/nestjs-best-practices/references/core-architecture.md), [references/database-integration.md](https://skilld.dev/api/skills-raw/ejirocodes/agent-skills/nestjs-best-practices/references/database-integration.md), [references/microservices.md](https://skilld.dev/api/skills-raw/ejirocodes/agent-skills/nestjs-best-practices/references/microservices.md), [references/openapi-graphql.md](https://skilld.dev/api/skills-raw/ejirocodes/agent-skills/nestjs-best-practices/references/openapi-graphql.md), [references/request-lifecycle.md](https://skilld.dev/api/skills-raw/ejirocodes/agent-skills/nestjs-best-practices/references/request-lifecycle.md), [references/testing.md](https://skilld.dev/api/skills-raw/ejirocodes/agent-skills/nestjs-best-practices/references/testing.md), [references/validation-pipes.md](https://skilld.dev/api/skills-raw/ejirocodes/agent-skills/nestjs-best-practices/references/validation-pipes.md).
>
> If the user asked to install this Skill, run `npx skilld install ejirocodes/agent-skills/nestjs-best-practices`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/nestjs-best-practices`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/ejirocodes/agent-skills/nestjs-best-practices) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/nestjs-best-practices`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/nestjs-best-practices --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/nestjs-best-practices --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# NestJS 11 Best Practices

## Quick Reference

| Topic | When to Use | Reference |
|-------|-------------|-----------|
| **Core Architecture** | Modules, Providers, DI, forwardRef, custom decorators | [core-architecture.md](https://skilld.dev/api/skills-raw/ejirocodes/agent-skills/nestjs-best-practices/references/core-architecture.md) |
| **Request Lifecycle** | Middleware, Guards, Interceptors, Pipes, Filters | [request-lifecycle.md](https://skilld.dev/api/skills-raw/ejirocodes/agent-skills/nestjs-best-practices/references/request-lifecycle.md) |
| **Validation & Pipes** | DTOs, class-validator, ValidationPipe, transforms | [validation-pipes.md](https://skilld.dev/api/skills-raw/ejirocodes/agent-skills/nestjs-best-practices/references/validation-pipes.md) |
| **Authentication** | JWT, Passport, Guards, Local/OAuth strategies, RBAC | [authentication.md](https://skilld.dev/api/skills-raw/ejirocodes/agent-skills/nestjs-best-practices/references/authentication.md) |
| **Database** | TypeORM, Prisma, Drizzle ORM, repository patterns | [database-integration.md](https://skilld.dev/api/skills-raw/ejirocodes/agent-skills/nestjs-best-practices/references/database-integration.md) |
| **Testing** | Unit tests, E2E tests, mocking providers | [testing.md](https://skilld.dev/api/skills-raw/ejirocodes/agent-skills/nestjs-best-practices/references/testing.md) |
| **OpenAPI & GraphQL** | Swagger decorators, resolvers, subscriptions | [openapi-graphql.md](https://skilld.dev/api/skills-raw/ejirocodes/agent-skills/nestjs-best-practices/references/openapi-graphql.md) |
| **Microservices** | TCP, Redis, NATS, Kafka patterns | [microservices.md](https://skilld.dev/api/skills-raw/ejirocodes/agent-skills/nestjs-best-practices/references/microservices.md) |

## Essential Patterns

### Module with Providers

```typescript
@Module({
  imports: [DatabaseModule],
  controllers: [UsersController],
  providers: [UsersService],
  exports: [UsersService], // Export for other modules
})
export class UsersModule {}
```

### Controller with Validation

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

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

  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) {
    return this.usersService.findOne(id);
  }
}
```

### DTO with Validation

```typescript
import { IsEmail, IsString, MinLength, IsOptional } from 'class-validator';

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

  @IsString()
  @MinLength(8)
  password: string;

  @IsOptional()
  @IsString()
  name?: string;
}
```

### Exception Filter

```typescript
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();

    response.status(status).json({
      statusCode: status,
      message: exception.message,
      timestamp: new Date().toISOString(),
    });
  }
}
```

### Guard with JWT

```typescript
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  canActivate(context: ExecutionContext) {
    return super.canActivate(context);
  }
}
```

## NestJS 11 Breaking Changes

- **Express v5**: Wildcards must be named (e.g., `*splat`), optional params use braces `/:file{.:ext}`
- **Node.js 20+**: Minimum required version
- **Fastify v5**: Updated adapter for Fastify users
- **Dynamic Modules**: Same module with identical config imported multiple times = separate instances

## Common Mistakes

1. **Not using `forwardRef()` for circular deps** - Causes "cannot resolve dependency" errors; wrap in `forwardRef(() => ModuleName)`
2. **Throwing plain errors instead of HttpException** - Loses status codes, breaks exception filters; use `throw new BadRequestException('message')`
3. **Missing `@Injectable()` decorator** - Provider won't be injectable; always decorate services
4. **Global ValidationPipe without `whitelist: true`** - Allows unexpected properties; set `whitelist: true, forbidNonWhitelisted: true`
5. **Importing modules instead of exporting providers** - Use `exports` array to share providers across modules
6. **Async config without `ConfigModule.forRoot()`** - ConfigService undefined; import ConfigModule in AppModule
7. **Testing without `overrideProvider()`** - Uses real services in unit tests; mock dependencies with `overrideProvider(Service).useValue(mock)`
8. **E2E tests sharing database state** - No isolation between tests; use transactions or truncate tables in beforeEach
