NestJS — progressive Node.js framework
NestJS is a framework for building efficient, scalable server-side Node.js applications.
It is TypeScript-first (works with plain JS too), heavily modular, and built around
dependency injection. Under the hood it runs on a pluggable HTTP platform — Express
(default, @nestjs/platform-express) or Fastify (@nestjs/platform-fastify) — and the
same building blocks also power GraphQL, WebSocket, and microservice apps. Its
architecture is heavily inspired by Angular: decorators + DI + modules.
This skill is a faithful offline copy of the official NestJS documentation. The narrative below
is the map; open the matching file under references/ for exact APIs, options, and full
detail. Start navigation at references/CONTENTS.md. Targets
NestJS v11; the live docs are at https://docs.nestjs.com.
Mental model — three building blocks
- Modules organize the app. Every app has a root
AppModule; features get their own
module. A @Module({ imports, controllers, providers, exports }) declares what it owns and
what it shares. → references/modules.md.
- Providers hold logic and are wired by dependency injection. Mark a class
@Injectable(), list it in a module's providers, and inject it via the constructor. Most
"services", repositories, factories, and helpers are providers. → references/components.md
(providers) and references/fundamentals/dependency-injection.md (custom providers).
- Controllers handle incoming requests and return responses. Decorators map routes to
handler methods. →
references/controllers.md.
import { Controller, Get } from '@nestjs/common';
import { CatsService } from './cats.service';
@Controller('cats')
export class CatsController {
constructor(private readonly catsService: CatsService) {} // DI by type
@Get()
findAll() {
return this.catsService.findAll();
}
}
import { Module } from '@nestjs/common';
@Module({
controllers: [CatsController],
providers: [CatsService], // available for DI within this module
exports: [CatsService], // share with modules that import this one
})
export class CatsModule {}
Setup & the entry point
$ npm i -g @nestjs/cli # the Nest CLI
$ nest new project-name # scaffold (asks package manager; --strict for strict TS)
$ nest g resource cats # generate a CRUD module+controller+service+DTOs
main.ts bootstraps the app with NestFactory:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
→ references/first-steps.md. For a non-HTTP app (CLI/cron/worker),
use NestFactory.createApplicationContext → references/application-context.md.
The CLI itself: references/cli/overview.md (monorepo
workspaces, libraries).
The request pipeline (canonical order)
This is the single most important thing to get right. A request flows through cross-cutting
components in a fixed order; globals run, then controller-bound, then route-bound (filters
are the exception — they resolve route → controller → global):
- Middleware — global, then module-bound (Express-style; runs before guards). →
references/middlewares.md
- Guards — authorization/authentication "can this proceed?" →
references/guards.md
- Interceptors (pre) — wrap the handler; can transform/observe. →
references/interceptors.md
- Pipes — validate & transform inputs (params/body/query). →
references/pipes.md
- Route handler — your controller method calls providers.
- Interceptors (post) — map/observe the response (RxJS, last-in-first-out).
- Exception filters — only on an uncaught error; format the response. →
references/exception-filters.md
Bind any of them at three levels: global (app.useGlobalX() or an APP_* provider token),
controller (decorator on the class), or route (decorator on the method). Read the exact
ordering rules — especially for pipes & interceptors — in references/faq/request-lifecycle.md.
Build your own request-shaped logic with custom decorators
and the execution context (ExecutionContext,
Reflector for reading metadata set by @SetMetadata).
Dependency injection & fundamentals
DI is resolved by type (the constructor param's class) or by token (@Inject(TOKEN)).
A provider is visible only within its module unless exports-ed and the consumer's module
imports it.
- Custom providers —
useClass / useValue / useFactory (with inject) / useExisting,
and non-class tokens. → references/fundamentals/dependency-injection.md
- Async providers —
useFactory returning a Promise (e.g. wait for a DB connection). → references/fundamentals/async-components.md
- Dynamic modules —
Module.forRoot()/forFeature() configurable modules. → references/fundamentals/dynamic-modules.md
- Injection scopes —
DEFAULT (singleton), REQUEST, TRANSIENT. Request scope has a
perf cost and bubbles up. → references/fundamentals/provider-scopes.md
- Circular dependency — break with
forwardRef(). → references/fundamentals/circular-dependency.md
- Module reference — resolve providers imperatively with
ModuleRef. → references/fundamentals/module-reference.md
- Lifecycle hooks —
OnModuleInit, OnApplicationBootstrap, OnModuleDestroy, OnApplicationShutdown (enable shutdown hooks for the last). → references/fundamentals/lifecycle-events.md
- Also: lazy-loading modules, discovery service, platform agnosticism.
Validation, configuration & databases
- Validation — the global
ValidationPipe + class-validator/class-transformer
decorators on DTOs (whitelist, transform, forbidNonWhitelisted). → references/techniques/validation.md
- Configuration —
@nestjs/config ConfigModule.forRoot() + ConfigService, .env,
validation schema, namespaced config. → references/techniques/configuration.md
- SQL (TypeORM / Sequelize) —
@nestjs/typeorm, forRoot/forFeature, repositories,
entities. → references/techniques/sql.md · recipes:
TypeORM, Sequelize,
Prisma, MikroORM.
- MongoDB (Mongoose) —
@nestjs/mongoose, schemas, models. → references/techniques/mongo.md
More techniques
Caching · Queues / BullMQ ·
Task scheduling / cron · Events ·
Logger · Serialization (ClassSerializerInterceptor) ·
Versioning · File upload ·
Streaming files · Server-Sent Events ·
Cookies · Sessions ·
Compression · HTTP module (HttpService/axios) ·
MVC · Performance (Fastify).
Security
Authentication (Passport strategies, JWT, @nestjs/passport/@nestjs/jwt; full Passport recipe: references/recipes/passport.md) ·
Authorization (RBAC, claims, CASL) ·
Rate limiting (@nestjs/throttler) ·
Helmet · CORS · CSRF ·
Encryption & hashing. Auth is typically a guard;
authorization combines a guard with metadata read via Reflector.
GraphQL, WebSockets & microservices
- GraphQL —
@nestjs/graphql with the Apollo (or Mercurius) driver; code-first
(decorators + generated SDL) or schema-first. Resolvers, mutations, subscriptions,
federation. → references/graphql/quick-start.md and the
rest of references/graphql/.
- WebSockets —
@WebSocketGateway() gateways (socket.io or ws), with the same
guards/pipes/interceptors/filters model. → references/websockets/gateways.md.
- Microservices —
@nestjs/microservices; choose a transporter (TCP, Redis, NATS, MQTT,
RabbitMQ, Kafka, gRPC) and use @MessagePattern (request-response) vs @EventPattern
(event). → references/microservices/basics.md and the
per-transport pages.
OpenAPI, testing & deployment
- OpenAPI / Swagger —
@nestjs/swagger SwaggerModule, @ApiProperty() etc., and the CLI
plugin that auto-infers schemas. → references/openapi/introduction.md.
- Testing —
@nestjs/testing Test.createTestingModule(...), .overrideProvider(...),
unit + e2e (supertest). → references/fundamentals/unit-testing.md
· Automock/Suites.
- Deployment →
references/deployment.md; serverless → references/faq/serverless.md;
Devtools graph → references/devtools/overview.md.
Recipes
Task-oriented guides: references/recipes/ — CRUD generator, REPL, CQRS,
SWC builder, hot reload, health checks (Terminus), Sentry, serve-static, router module,
nest-commander, async local storage, Compodoc, and more. Browse references/CONTENTS.md.
Gotchas
- "Nest can't resolve dependencies of X" — the dependency isn't a
provider in the current
module, or its owning module doesn't exports it and isn't imports-ed. Check the module
graph first. → references/faq/errors.md
- Decorators need TS config —
experimentalDecorators + emitDecoratorMetadata, and
reflect-metadata imported once. DI by type relies on emitted metadata.
- Global pipes/guards/etc. set via
app.useGlobalX() can't inject — to use DI in a global,
register it as an APP_PIPE / APP_GUARD / APP_INTERCEPTOR / APP_FILTER provider instead.
ValidationPipe does nothing useful without DTOs decorated with class-validator, and
needs transform: true to instantiate DTO classes / coerce types. Use whitelist to strip
unknown props.
- Circular
imports/providers — use forwardRef() on both sides; prefer restructuring.
- Request-scoped providers make the whole injection chain request-scoped — measurable
overhead; keep them shallow.
- Pipe & interceptor binding order is not simply top-to-bottom — parameter pipes resolve
last-param-to-first; read
references/faq/request-lifecycle.md.
- Keep
@nestjs/* versions aligned (core/common/platform and the ecosystem packages move
together across majors). This bundle targets v11.
Provenance
references/ is converted from the official nestjs/docs.nestjs.com
content/ source (the same Markdown that powers https://docs.nestjs.com) by
tools/build_references.py — the TS/JS @@switch snippets are reduced to their canonical
TypeScript form, promo banners are dropped, and links are absolutized to the live site.
Every page keeps a > Source: link to its upstream file on GitHub. Redistributed under the
upstream MIT license (Kamil Myśliwiec) — see references/LICENSE.
1---2name: nestjs3description: Build server-side applications with NestJS (Nest) — the progressive, TypeScript-first Node.js framework. Use when working with `@nestjs/*` packages, the `nest` CLI (`nest new`, `nest g`), or any NestJS building block: controllers & routing (`@Controller`, `@Get`/`@Post`), providers & dependency injection (`@Injectable`, custom providers, injection scopes), modules (`@Module`, dynamic/shared/global modules), and the request pipeline — middleware, guards (`@UseGuards`), interceptors, pipes & validation (`ValidationPipe`, class-validator), exception filters, and custom decorators. Covers configuration (`@nestjs/config`), databases (TypeORM, Sequelize, Mongoose, Prisma, MikroORM), techniques (caching, queues/BullMQ, scheduling, events, logging, serialization, versioning, file upload, SSE), security (Passport/JWT auth, RBAC/CASL authorization, helmet, CORS, CSRF, rate limiting/throttler), GraphQL (code-first & schema-first, Apollo, federation), WebSockets (gateways), microservices (TCP/Redis/Kafka/NATS/MQTT/Rabbit4license: MIT5---67# NestJS — progressive Node.js framework89NestJS is a framework for building **efficient, scalable server-side Node.js applications**.10It is **TypeScript-first** (works with plain JS too), heavily **modular**, and built around11**dependency injection**. Under the hood it runs on a pluggable HTTP platform — **Express**12(default, `@nestjs/platform-express`) or **Fastify** (`@nestjs/platform-fastify`) — and the13same building blocks also power **GraphQL**, **WebSocket**, and **microservice** apps. Its14architecture is heavily inspired by Angular: decorators + DI + modules.1516This skill is a faithful offline copy of the official NestJS documentation. The narrative below17is the map; **open the matching file under `references/` for exact APIs, options, and full18detail.** Start navigation at [`references/CONTENTS.md`](references/CONTENTS.md). Targets19**NestJS v11**; the live docs are at https://docs.nestjs.com.2021## Mental model — three building blocks22231. **Modules** organize the app. Every app has a root `AppModule`; features get their own24 module. A `@Module({ imports, controllers, providers, exports })` declares what it owns and25 what it shares. → [`references/modules.md`](references/modules.md).262. **Providers** hold logic and are wired by **dependency injection**. Mark a class27 `@Injectable()`, list it in a module's `providers`, and inject it via the constructor. Most28 "services", repositories, factories, and helpers are providers. → [`references/components.md`](references/components.md)29 (providers) and [`references/fundamentals/dependency-injection.md`](references/fundamentals/dependency-injection.md) (custom providers).303. **Controllers** handle incoming requests and return responses. Decorators map routes to31 handler methods. → [`references/controllers.md`](references/controllers.md).3233```typescript title="cats.controller.ts"34import { Controller, Get } from '@nestjs/common';35import { CatsService } from './cats.service';3637@Controller('cats')38export class CatsController {39 constructor(private readonly catsService: CatsService) {} // DI by type4041 @Get()42 findAll() {43 return this.catsService.findAll();44 }45}46```4748```typescript title="cats.module.ts"49import { Module } from '@nestjs/common';5051@Module({52 controllers: [CatsController],53 providers: [CatsService], // available for DI within this module54 exports: [CatsService], // share with modules that import this one55})56export class CatsModule {}57```5859## Setup & the entry point6061```bash62$ npm i -g @nestjs/cli # the Nest CLI63$ nest new project-name # scaffold (asks package manager; --strict for strict TS)64$ nest g resource cats # generate a CRUD module+controller+service+DTOs65```6667`main.ts` bootstraps the app with `NestFactory`:6869```typescript title="main.ts"70import { NestFactory } from '@nestjs/core';71import { AppModule } from './app.module';7273async function bootstrap() {74 const app = await NestFactory.create(AppModule);75 await app.listen(process.env.PORT ?? 3000);76}77bootstrap();78```7980→ [`references/first-steps.md`](references/first-steps.md). For a non-HTTP app (CLI/cron/worker),81use `NestFactory.createApplicationContext` → [`references/application-context.md`](references/application-context.md).82The CLI itself: [`references/cli/overview.md`](references/cli/overview.md) (monorepo83[workspaces](references/cli/workspaces.md), [libraries](references/cli/libraries.md)).8485## The request pipeline (canonical order)8687This is the single most important thing to get right. A request flows through cross-cutting88components in a **fixed order**; globals run, then controller-bound, then route-bound (filters89are the exception — they resolve route → controller → global):90911. **Middleware** — global, then module-bound (Express-style; runs before guards). → [`references/middlewares.md`](references/middlewares.md)922. **Guards** — authorization/authentication "can this proceed?" → [`references/guards.md`](references/guards.md)933. **Interceptors (pre)** — wrap the handler; can transform/observe. → [`references/interceptors.md`](references/interceptors.md)944. **Pipes** — validate & transform inputs (params/body/query). → [`references/pipes.md`](references/pipes.md)955. **Route handler** — your controller method calls providers.966. **Interceptors (post)** — map/observe the response (RxJS, last-in-first-out).977. **Exception filters** — only on an uncaught error; format the response. → [`references/exception-filters.md`](references/exception-filters.md)9899Bind any of them at three levels: **global** (`app.useGlobalX()` or an `APP_*` provider token),100**controller** (decorator on the class), or **route** (decorator on the method). Read the exact101ordering rules — especially for pipes & interceptors — in [`references/faq/request-lifecycle.md`](references/faq/request-lifecycle.md).102Build your own request-shaped logic with [custom decorators](references/custom-decorators.md)103and the [execution context](references/fundamentals/execution-context.md) (`ExecutionContext`,104`Reflector` for reading metadata set by `@SetMetadata`).105106## Dependency injection & fundamentals107108DI is resolved by **type** (the constructor param's class) or by **token** (`@Inject(TOKEN)`).109A provider is visible only within its module unless `exports`-ed and the consumer's module110`imports` it.111112- **Custom providers** — `useClass` / `useValue` / `useFactory` (with `inject`) / `useExisting`,113 and non-class tokens. → [`references/fundamentals/dependency-injection.md`](references/fundamentals/dependency-injection.md)114- **Async providers** — `useFactory` returning a Promise (e.g. wait for a DB connection). → [`references/fundamentals/async-components.md`](references/fundamentals/async-components.md)115- **Dynamic modules** — `Module.forRoot()/forFeature()` configurable modules. → [`references/fundamentals/dynamic-modules.md`](references/fundamentals/dynamic-modules.md)116- **Injection scopes** — `DEFAULT` (singleton), `REQUEST`, `TRANSIENT`. Request scope has a117 perf cost and bubbles up. → [`references/fundamentals/provider-scopes.md`](references/fundamentals/provider-scopes.md)118- **Circular dependency** — break with `forwardRef()`. → [`references/fundamentals/circular-dependency.md`](references/fundamentals/circular-dependency.md)119- **Module reference** — resolve providers imperatively with `ModuleRef`. → [`references/fundamentals/module-reference.md`](references/fundamentals/module-reference.md)120- **Lifecycle hooks** — `OnModuleInit`, `OnApplicationBootstrap`, `OnModuleDestroy`, `OnApplicationShutdown` (enable shutdown hooks for the last). → [`references/fundamentals/lifecycle-events.md`](references/fundamentals/lifecycle-events.md)121- Also: [lazy-loading modules](references/fundamentals/lazy-loading-modules.md), [discovery service](references/fundamentals/discovery-service.md), [platform agnosticism](references/fundamentals/platform-agnosticism.md).122123## Validation, configuration & databases124125- **Validation** — the global `ValidationPipe` + `class-validator`/`class-transformer`126 decorators on DTOs (`whitelist`, `transform`, `forbidNonWhitelisted`). → [`references/techniques/validation.md`](references/techniques/validation.md)127- **Configuration** — `@nestjs/config` `ConfigModule.forRoot()` + `ConfigService`, `.env`,128 validation schema, namespaced config. → [`references/techniques/configuration.md`](references/techniques/configuration.md)129- **SQL (TypeORM / Sequelize)** — `@nestjs/typeorm`, `forRoot`/`forFeature`, repositories,130 entities. → [`references/techniques/sql.md`](references/techniques/sql.md) · recipes:131 [TypeORM](references/recipes/sql-typeorm.md), [Sequelize](references/recipes/sql-sequelize.md),132 [Prisma](references/recipes/prisma.md), [MikroORM](references/recipes/mikroorm.md).133- **MongoDB (Mongoose)** — `@nestjs/mongoose`, schemas, models. → [`references/techniques/mongo.md`](references/techniques/mongo.md)134135## More techniques136137[Caching](references/techniques/caching.md) · [Queues / BullMQ](references/techniques/queues.md) ·138[Task scheduling / cron](references/techniques/task-scheduling.md) · [Events](references/techniques/events.md) ·139[Logger](references/techniques/logger.md) · [Serialization](references/techniques/serialization.md) (`ClassSerializerInterceptor`) ·140[Versioning](references/techniques/versioning.md) · [File upload](references/techniques/file-upload.md) ·141[Streaming files](references/techniques/streaming-files.md) · [Server-Sent Events](references/techniques/server-sent-events.md) ·142[Cookies](references/techniques/cookies.md) · [Sessions](references/techniques/sessions.md) ·143[Compression](references/techniques/compression.md) · [HTTP module](references/techniques/http-module.md) (`HttpService`/axios) ·144[MVC](references/techniques/mvc.md) · [Performance (Fastify)](references/techniques/performance.md).145146## Security147148[Authentication](references/security/authentication.md) (Passport strategies, JWT, `@nestjs/passport`/`@nestjs/jwt`; full Passport recipe: [`references/recipes/passport.md`](references/recipes/passport.md)) ·149[Authorization](references/security/authorization.md) (RBAC, claims, CASL) ·150[Rate limiting](references/security/rate-limiting.md) (`@nestjs/throttler`) ·151[Helmet](references/security/helmet.md) · [CORS](references/security/cors.md) · [CSRF](references/security/csrf.md) ·152[Encryption & hashing](references/security/encryption-hashing.md). Auth is typically a **guard**;153authorization combines a guard with metadata read via `Reflector`.154155## GraphQL, WebSockets & microservices156157- **GraphQL** — `@nestjs/graphql` with the Apollo (or Mercurius) driver; **code-first**158 (decorators + generated SDL) or **schema-first**. Resolvers, mutations, subscriptions,159 federation. → [`references/graphql/quick-start.md`](references/graphql/quick-start.md) and the160 rest of `references/graphql/`.161- **WebSockets** — `@WebSocketGateway()` gateways (socket.io or ws), with the same162 guards/pipes/interceptors/filters model. → [`references/websockets/gateways.md`](references/websockets/gateways.md).163- **Microservices** — `@nestjs/microservices`; choose a transporter (TCP, Redis, NATS, MQTT,164 RabbitMQ, Kafka, gRPC) and use `@MessagePattern` (request-response) vs `@EventPattern`165 (event). → [`references/microservices/basics.md`](references/microservices/basics.md) and the166 per-transport pages.167168## OpenAPI, testing & deployment169170- **OpenAPI / Swagger** — `@nestjs/swagger` `SwaggerModule`, `@ApiProperty()` etc., and the CLI171 plugin that auto-infers schemas. → [`references/openapi/introduction.md`](references/openapi/introduction.md).172- **Testing** — `@nestjs/testing` `Test.createTestingModule(...)`, `.overrideProvider(...)`,173 unit + e2e (`supertest`). → [`references/fundamentals/unit-testing.md`](references/fundamentals/unit-testing.md)174 · [Automock/Suites](references/recipes/suites.md).175- **Deployment** → [`references/deployment.md`](references/deployment.md); serverless → [`references/faq/serverless.md`](references/faq/serverless.md);176 **Devtools** graph → [`references/devtools/overview.md`](references/devtools/overview.md).177178## Recipes179180Task-oriented guides: [`references/recipes/`](references/recipes/) — CRUD generator, REPL, CQRS,181SWC builder, hot reload, health checks (Terminus), Sentry, serve-static, router module,182nest-commander, async local storage, Compodoc, and more. Browse [`references/CONTENTS.md`](references/CONTENTS.md).183184## Gotchas185186- **"Nest can't resolve dependencies of X"** — the dependency isn't a `provider` in the current187 module, or its owning module doesn't `exports` it and isn't `imports`-ed. Check the module188 graph first. → [`references/faq/errors.md`](references/faq/errors.md)189- **Decorators need TS config** — `experimentalDecorators` + `emitDecoratorMetadata`, and190 `reflect-metadata` imported once. DI by type relies on emitted metadata.191- **Global pipes/guards/etc. set via `app.useGlobalX()` can't inject** — to use DI in a global,192 register it as an `APP_PIPE` / `APP_GUARD` / `APP_INTERCEPTOR` / `APP_FILTER` provider instead.193- **`ValidationPipe` does nothing useful without DTOs** decorated with `class-validator`, and194 needs `transform: true` to instantiate DTO classes / coerce types. Use `whitelist` to strip195 unknown props.196- **Circular `imports`/providers** — use `forwardRef()` on both sides; prefer restructuring.197- **Request-scoped providers** make the whole injection chain request-scoped — measurable198 overhead; keep them shallow.199- **Pipe & interceptor binding order is not simply top-to-bottom** — parameter pipes resolve200 last-param-to-first; read [`references/faq/request-lifecycle.md`](references/faq/request-lifecycle.md).201- **Keep `@nestjs/*` versions aligned** (core/common/platform and the ecosystem packages move202 together across majors). This bundle targets **v11**.203204## Provenance205206`references/` is converted from the official **[nestjs/docs.nestjs.com](https://github.com/nestjs/docs.nestjs.com)**207`content/` source (the same Markdown that powers https://docs.nestjs.com) by208`tools/build_references.py` — the TS/JS `@@switch` snippets are reduced to their canonical209**TypeScript** form, promo banners are dropped, and links are absolutized to the live site.210Every page keeps a `> Source:` link to its upstream file on GitHub. Redistributed under the211upstream **MIT license** (Kamil Myśliwiec) — see [`references/LICENSE`](references/LICENSE).