nestjs/nest
github.com/nestjs/nest ↗ · 2465 files · 5.3 MB
[source preview omitted from public export]
Overview
Nest is a TypeScript framework for developers building Node.js HTTP services, message-driven microservices, and WebSocket applications. Its core assembles decorator-defined modules into a dependency graph and runs controller methods through guards, pipes, interceptors, and platform adapters. This checkout contains the framework packages, runnable integration examples, sample applications, and contributor tooling; database persistence belongs to application integrations such as the TypeORM sample rather than the core dependency container.
System map
The repository is a framework monorepo with independently published packages and application examples. Core owns module discovery, dependency construction, application lifecycle, and route execution. Platform packages provide native HTTP implementations, while optional packages supply messaging and sockets. npm scripts and CircleCI describe compilation and verification, with package publication handled through Lerna.
- The root defines npm workspaces over packages/*, while common and core publish ESM index.js entrypoints and internal subpath exports.
- NestFactoryStatic exposes create, createMicroservice, and createApplicationContext for HTTP, transport, and standalone dependency-container runtimes.
- HTTP creation defaults to dynamically loading ExpressAdapter; callers can supply an AbstractHttpAdapter.
- DependenciesScanner discovers module imports and binds global scope; InstanceLoader constructs providers, injectables, and controllers.
- ServerFactory dispatches Redis, NATS, MQTT, gRPC, Kafka, and RabbitMQ transports, falling back to TCP.
- The inspected persistence example delegates MySQL configuration and repository registration to @nestjs/typeorm rather than storing records in NestContainer.
- Root scripts compile TypeScript project references, relocate built packages, run Vitest, lint with oxlint, and publish through Lerna.
- Node.js >=20 is required; TypeScript targets ES2023 with Node16 module resolution and emitted legacy decorator metadata.
- CircleCI defines build, unit-test matrix, lint, Docker-backed integration, and sample-build jobs.
Feature catalog
The principal user is an application developer composing modules, providers, controllers, and transport handlers. The inspected examples expose HTTP resource operations, socket messages, TCP request-response, database repositories, Swagger documentation, and GraphQL configuration. Framework APIs add validation, response handling, route diagnostics, and security helpers. This catalog covers inspected surfaces rather than every sample or public export.
- The cats sample exposes POST /cats, GET /cats, and GET /cats/:id; the last handler parses and logs an ID rather than retrieving a record.
- The TypeORM sample exposes create, list, lookup, and delete operations under /users.
- EventsGateway emits three events responses for the events message and echoes identity message data.
- The microservices sample runs HTTP on port 3001 alongside TCP; its HTTP handler sends a sum command and its MessagePattern handler reduces numeric input.
- The Swagger sample constructs a bearer-auth documented Cats API and mounts its generated documentation at api.
- The schema-first GraphQL sample selects ApolloDriver, loads .graphql definitions, transforms an upper directive, and enables subscription handlers.
- ValidationPipe supports transformation, custom validator and transformer packages, custom exception creation, and list or grouped validation errors.
- NestApplication exposes CORS, cross-origin CSRF protection, security headers, and API versioning configuration.
- RouterResponseController supports ordinary replies, redirects, template rendering, and observable result conversion.
- Route registration can collect diagnostics and sort by specificity before applying a conflict policy and registering routes.
Data flow
Decorator metadata enters module scanning and becomes container-owned instances and registered routes. HTTP requests pass through contextual guards, interceptors, and parameter pipes before reaching application methods. Application state can remain in a provider or move through a repository into an external database. Results return through framework response normalization and native adapter serialization.
- Module scanning merges reflected imports with dynamic-module imports, unwraps promises and forward references, and recursively scans dependencies.
- InstanceLoader creates prototypes first, then asynchronously creates module instances and records graph inspection data.
- Injector.loadInstance selects an instance by context and inquirer, detects pending dependency cycles, and combines constructor instantiation with property injection.
- RoutesResolver enumerates container controllers, combines prefix, module path, controller path, and version metadata, then delegates exploration.
- HTTP execution prepares contextual pipes, guards, and interceptors; its handler applies pipes before callback.apply(instance, args).
- For a metatype selected for DTO validation, ValidationPipe strips prototype keys, converts plain input to that metatype, validates it, and throws an exception generated from validation errors. Without a metatype or when toValidate() is false, it instead returns the input or applies primitive transformation.
- CatsService owns an in-memory Cat array; create appends to it and findAll resolves that same array.
- UsersService maps firstName and lastName into User and passes it to repository.save; reads and deletes use repository methods.
- Observable HTTP results are converted with lastValueFrom; ExpressAdapter serializes objects as JSON and other ordinary values as strings.
- StreamableFile wraps a buffer or existing Readable; ExpressAdapter applies stream headers, pipes to the response, and destroys unfinished streams when the response finishes.
Behavior traces
Three concrete flows were followed through source: HTTP startup, cats request handling, and TypeORM persistence. Startup separates dependency construction from later application initialization and listener creation. Request execution separates authorization from parameter transformation and wraps controller invocation with interceptors. Persistence is an application-level repository operation, with framework dependency injection supplying the repository.
- Startup step 1: cats bootstrap calls NestFactory.create(AppModule), installs ValidationPipe globally, and calls listen(3000).
- Startup step 2: NestFactory.create constructs ApplicationConfig and NestContainer, invokes initialize, creates NestApplication, preloads optional packages, and returns an adapter proxy.
- Startup step 3: initialize calls DependenciesScanner.scan, InstanceLoader.createInstancesOfDependencies, and applyApplicationProviders in that order.
- Startup step 4: listen calls init if needed; init registers parsers, modules, routes, initialization hooks, router error handlers, and bootstrap hooks before adapter.listen opens the listener.
- Cats POST step 1: controller metadata selects RolesGuard and the admin role; RolesGuard.canActivate reads role metadata and checks request.user.roles.
- Cats POST step 2: the execution closure runs guards, invokes interceptors around the handler, applies parameter pipes, and calls CatsController.create, which appends through CatsService.create.
- Cats GET follows CatsController.findAll to CatsService.findAll; the provider returns a promise containing the current in-memory array.
- Persistence setup: AppModule configures MySQL with entity autoloading; UsersModule.forFeature([User]) registers the repository injected into UsersService.
- Persistence write: POST /users calls UsersController.create, then UsersService.create, then repository.save(new User populated from the DTO), returning the resulting Promise<User>.
Testing signals
Tests and CI were inspected, not executed; no passing result or coverage percentage is established. Root Vitest configurations distinguish package unit tests from integration fixtures and explicitly preserve decorator behavior. Inspected tests cover injection, route tokenization, cross-origin decisions, HTTP responses, streaming, and mocked repository operations. Coverage exclusions, skipped tests, and integration exclusions limit what those configured checks can establish.
- The configured unit command is vitest run; its source configuration includes package specs, enables globals, aliases framework packages, and loads reflect-metadata.
- Vitest uses a resolver plugin to prefer TypeScript over adjacent compiled .js files and explicitly enables legacy decorator metadata.
- Integration Vitest selects integration specs, disables file parallelism, and gives tests and hooks 30-second timeouts.
- Integration configuration excludes GraphQL code-first, inspector, and one REPL suite with comments describing module identity, fixture, and export-resolution problems.
- Inspected Injector tests construct decorated constructor and property dependencies; route-conflict tests assert literal, parameter, and wildcard token classification.
- Cross-origin unit cases explicitly cover safe methods, method case sensitivity, same-origin fetch metadata, cross-site requests, and sibling-subdomain rejection.
- The hello-world integration suite uses Supertest to assert host routing, headers, async responses, and Observable responses, closing applications after tests.
- UsersService tests replace the repository token with vi.fn mocks; these assertions cover service delegation rather than a real MySQL connection.
- Streaming integration assertions cover streams, buffers, RxJS, headers, and missing files; one client-cancellation test is explicitly skipped as flaky.
- Coverage uses V8 and excludes adapters, nest-* runtime files, and several discovery, middleware, and transport modules; root coverage scripts suppress failure status with || true.
- Inspected CircleCI configuration runs a Node-version unit matrix and separate integration jobs; GitHub CodeQL config selects security-extended queries.
Risk map
These are source observations and explicitly labeled hypotheses, not confirmed vulnerabilities. Important boundaries include input transformation, application-provided authorization, browser-origin checks, cookie signing, file streaming, and tooling subprocesses. Several runtime paths are excluded from coverage measurement, and integration exclusions leave configured verification gaps. Framework-wide changes to injection or adapter semantics have a broad compatibility surface.
- Initialization errors abort the process by default; setting abortOnError:false selects rethrow behavior instead.
- The cats role guard depends on request.user supplied elsewhere; handlers without role metadata are allowed by this guard.
- Cross-origin protection deliberately permits GET, HEAD, OPTIONS, and requests without Origin or Sec-Fetch-Site; it is not a general authentication boundary.
- Route-based CSRF exclusions fail closed for noncanonical paths, while a configured exclusion predicate returns its own decision directly.
- CookieSigner validates nonempty signing secrets, uses HMAC-SHA256, verifies all rotation secrets, and compares equal-length signatures with timingSafeEqual.
- Hypothesis: different ValidationPipe instances supplying custom packages may interact because validator and transformer references are module-level variables reassigned by constructors. (inferred)
- The SQL sample enables synchronize:true; its startup therefore includes ORM-managed schema synchronization and warrants review before reuse with valuable data.
- StreamableFile's default pre-header error handler sends err.message in a 400 response; applications can replace that handler.
- Adapter compatibility includes direct Node response writes and net.Server assumptions, beyond the nominal abstract method interface.
- Docker tooling forwards CLI arguments into spawnSync and enables shell execution on Windows; this is an inspected contributor-tool subprocess boundary.
- The PR content guard uses pull_request_target with comment-write permission but reads changed content through APIs; it flags incomplete scans at GitHub's 3000-file limit.
- Coverage command failure suppression and excluded integration suites mean successful CI job completion alone cannot establish every inspected critical flow passed. (inferred)
Extension points
Nest offers explicit extension seams through module metadata, decorators, provider tokens, adapters, and contextual request processing. Discovery APIs expose metadata-indexed provider and controller collections. Testing overrides reuse production scanning and instantiation rather than requiring a separate application architecture. Transport selection and optional integration modules provide additional runtime composition boundaries.
- Root modules may be classes, dynamic modules, forward references, or promises; the scanner merges dynamic imports into reflected imports.
- A custom HTTP implementation plugs into NestFactory.create through AbstractHttpAdapter and the HttpServer contract.
- Context creators assemble pipes, guards, and interceptors for controller methods using module and request-context identifiers.
- ParameterDecoratorOptions accepts a StandardSchemaV1 and pipe list; assignMetadata normalizes both options and legacy positional signatures.
- DiscoveryService.createDecorator creates a metadata key and records discoverable class links; getProviders and getControllers can select by metadata key.
- TestingModuleBuilder exposes provider, module, pipe, guard, interceptor, and filter overrides plus a mocker callback.
- Testing overrides support useValue, useFactory, and useClass replacements applied through container.replace.
- ValidationPipe accepts injected validator and transformer implementations and a custom exceptionFactory.
- ServerFactory is the built-in transport dispatch table; application MessagePattern decorators define transport-level handlers.
- Hybrid applications can attach microservices sharing the container and optionally inherit HTTP application configuration.
- StreamableFile exposes replaceable error-handler and error-logger callbacks for application-specific streaming policy.
Contributor handoff
This brief is bounded to the inspected tracked sources at the pinned commit. Tests and CI were inspected, not executed, and no runtime or performance result is claimed. Start changes at the owning package and follow its public contract into a representative integration fixture. Preserve ESM import conventions, decorator metadata, adapter behavior, and existing test configuration; treat sample settings and coverage output cautiously.
- Read root scripts and the owning package manifest first: root version is 12.0.0, while inspected common/core manifests and Lerna use 12.1.2.
- Preserve .js relative import suffixes in TypeScript and the Node16 resolution/decorator settings.
- For startup edits, read NestFactory.initialize, DependenciesScanner.scan, InstanceLoader, and NestApplication.init before changing ordering.
- For adapter work, inspect the AbstractHttpAdapter contract and native stream behavior; the interface documents request and Node-server assumptions.
- For later authorized verification, npm test selects package unit specs directly from source; contributor documentation states these need neither a build nor Docker.
- Integration preparation builds framework packages into node_modules/@nestjs and starts Docker services; inspect that environment requirement before running integration commands.
- Tests and CI in this report were inspected only; configured commands and assertions are evidence of intended checks, not executed passing results.
- Do not use coverage scripts as failure gates without accounting for || true and central runtime exclusions.
- Use TestingModuleBuilder overrides and repository-token mocks to isolate application services; the SQL sample demonstrates this pattern.
- Keep compatibility handling in assignMetadata when editing parameter decorators; it explicitly supports callers using the pre-v12 positional signature.
- Route diagnostics must run before duplicate-rejecting adapter registration; specificity sorting also affects which route is reported as the winner.
Languages
| Language | Files | Share of source |
|---|---|---|
| TypeScript | 1966 | 99% |
| JSON | 243 | docs/config |
| Markdown | 43 | docs/config |
| YAML | 21 | docs/config |
| JavaScript | 10 | 1% |
| HTML | 4 | docs/config |
| SQL | 4 | 0% |
| Shell | 4 | 0% |
Start reading here
Probable source entrypoint: packages/ — inferred from the directory tree and manifest, not the upstream docs.
Source roots
packages/ (1027 files)
Repository structure
| Top-level path | Files |
|---|---|
packages/ | 1027 |
sample/ | 746 |
integration/ | 630 |
tools/ | 18 |
.github/ | 11 |
scripts/ | 6 |
.husky/ | 2 |
.circleci/ | 1 |
Docs found: CONTRIBUTING.mdReadme.md
Package
package.json — @nestjs/core v12.0.0, 80 declared dependencies.
@apollo/server@as-integrations/express5@commitlint/cli@commitlint/config-angular@fastify/cors@fastify/formbody@fastify/middie@fastify/multipart@fastify/static@fastify/view@grpc/grpc-js@grpc/proto-loader
CI & config entrypoints
.github/workflows/codeql-analysis.yml— GitHub Actions workflow.github/workflows/pr-content-guard.yml— GitHub Actions workflowpackage.json— npm scripts: build, build:dev, build:prod, build:samples, changelog, clean, codechecks:benchmarks, coveragesample/01-cats-app/package.json— npm scripts: build, format, lint, prebuild, start, start:debug, start:dev, start:prodsample/02-gateways/package.json— npm scripts: build, format, lint, prebuild, start, start:debug, start:dev, start:prodsample/03-microservices/package.json— npm scripts: build, format, lint, prebuild, start, start:debug, start:dev, start:prodsample/04-grpc/package.json— npm scripts: build, format, lint, prebuild, start, start:debug, start:dev, start:prodsample/05-sql-typeorm/package.json— npm scripts: build, format, lint, prebuild, start, start:debug, start:dev, start:prodsample/06-mongoose/package.json— npm scripts: build, format, lint, prebuild, start, start:debug, start:dev, start:prodsample/07-sequelize/package.json— npm scripts: build, format, lint, prebuild, start, start:debug, start:dev, start:prod
Structural health signals
Average score 7.5/10 across 96 analyzed source files; 12 hotspots surfaced.
packages/core/injector/injector.ts— 1368 lines, score 5.5 (Large file, Deep nesting)packages/common/services/console-logger.service.ts— 940 lines, score 5.5 (Large file, Deep nesting)packages/platform-fastify/adapters/fastify-adapter.ts— 1269 lines, score 5.7 (Large file, Deep nesting)
These are deterministic review leads — size, churn, and structural signals — not proof of a bug in this project.
Recent history
35142c3eca8e2026-10-02 — chore(deps): update vitest monorepo to v5.0.3 (#17899)2e78adf8ea722026-10-02 — fix(websockets): resolve global scoped enhancers per connection (#17979)52687474b4e72026-10-02 — fix(core): settle SSE lifecycle on early disconnect (#17987)b64b3a054bc42026-10-02 — fix(express): destroy the `StreamableFile` source on client disconnect (#17973)0853427785382026-10-02 — fix(deps): update graphql-tools monorepo (#17967)