Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Nestjs Knowledge Patch?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/nevaberry-nestjs-knowledge-patch-nevaberry-plugins)
---
name: nestjs-knowledge-patch
description: NestJS
version: "11.1.x selected changes"
license: MIT
metadata:
author: Nevaberry
---
# NestJS Knowledge Patch
Use this skill when upgrading NestJS or working on HTTP routes, middleware,
validation, module construction, configuration, microservices, gateways, or
observability. Load the reference for the task; its guidance retains the
version and adapter conditions for each behavior.
## Reference index
| Reference | Topics |
| --- | --- |
| [Platform, HTTP, and Lifecycle](references/platform-http-and-lifecycle.md) | Runtime requirements, HTTP adapters, routes, middleware, versioning, security, validation, uploads, streams, SSE, lifecycle, and limit defaults |
| [Modules, Configuration, and Services](references/modules-configuration-and-services.md) | CLI upgrades and builds, configuration, cache, health checks, module identity, lazy loading, dependency scopes, decorators, testing, and GraphQL |
| [Microservices and Observability](references/microservices-and-observability.md) | Transport options, request failures, shutdown, NATS, TCP, RabbitMQ, MQTT, Redis, Kafka, gRPC, WebSockets, instrumentation, and logging |
## Breaking changes and deprecations
### Runtime and CLI requirements
Core packages in NestJS 12 ship as ESM and require Node.js 20.19+ on the 20.x
line or 22.12+. Existing CommonJS applications can load them through Node's
`require(esm)`.
`nest new`, `nest generate`, and `nest upgrade` inherit the
`@nestjs/schematics` requirement: use Node.js 22.22.3+ on 22.x, 24.15+ on
24.x, or 26+. The project-local CLI upgrade preserves the project's existing
CommonJS or ESM format.
### Route strings and middleware
NestJS 11 automatically converts legacy Express wildcard patterns. Use
`@Get('users/*splat')` for paths below `users`, and `forRoutes('{*splat}')`
for middleware that also runs on the root path. Express 5 literal route
characters such as `(`, `)`, `[`, `]`, `?`, `+`, and `!` need a backslash;
quote parameter names that are invalid JavaScript identifiers.
Fastify controller routes keep their wildcard syntax. For middleware registered
through `MiddlewareConsumer`, migrate `forRoutes('(.*)')` to
`forRoutes('*splat')`; NestJS 11 converts the legacy middleware pattern.
On Fastify 11.2.11, use `forRoutes('{*path}')` to include `/`, because
`*path` matches only subpaths after that release's `@fastify/middie` update.
Fastify allows only CORS-safelisted methods by default. List the methods the
application needs, including any safelisted methods clients use:
```typescript
app.enableCors({ methods: ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'] });
```
### Module identity and lifecycle ordering
NestJS 11 deduplicates dynamic modules by object reference. Save the result of
`TypeOrmModule.forFeature([User])` and import that same object wherever the
module should share an instance. A module's `exports` array no longer supports
promise entries; export the provider token or module directly.
In NestJS 11, `onModuleDestroy`, `beforeApplicationShutdown`, and
`onApplicationShutdown` traverse modules in reverse initialization order.
Global modules initialize first and shut down last. In NestJS 12, lifecycle
hooks run by component hierarchy level; review initialization and teardown
code and tests that rely on relative provider or module ordering.
### Transport and GraphQL migrations
For the NATS v3 migration, replace `nats` with `@nats-io/transport-node` in
dependencies and direct imports. Packets are serialized as JSON strings;
custom deserializers receive the full NATS message. Read its payload with
`msg.json()` and import the header factory from `@nats-io/nats-core`.
Starting in 12.2.0, TCP, Redis, NATS, MQTT, and RabbitMQ warn when an
`@EventPattern()` handler replies to `ClientProxy#send()`. Switch request/reply
handlers to `@MessagePattern()` before the next major version and use `emit()`
for events.
Migrate `subscriptions-transport-ws` to `graphql-ws` on both server and clients:
the protocols are wire-incompatible. Review `onConnect` callbacks. GraphiQL is
the default IDE; replace `playground` with `graphiql` and use an options object
to customize it.
### Configuration, caching, and health indicators
In `@nestjs/config` 4, `ConfigService.get()` checks internal namespaces or
custom config files, then validated environment values, then `process.env`.
Set `skipProcessEnv: true` in `ConfigModule.forRoot()` to skip the direct
`process.env` lookup.
Replace deprecated `ignoreEnvVars` with
`ConfigModule.forRoot({ validatePredefined: false })` to exclude variables
already in `process.env` when the module loads. Variables loaded by the module
from a `.env` file remain eligible for validation.
For external caches, replace singular `store` with a `stores` array of Keyv
adapters. Keyv stores an envelope with `value` and `expires` and unwraps
`value` through its API. Account for the format when reading the backend
directly or needing entries written by the previous cache manager.
For custom Terminus indicators, inject `HealthIndicatorService` from
`TerminusModule` and return `check(key).up()` or `check(key).down()`.
A down result can carry metadata or a message string. Legacy `HealthIndicator`
and `HealthCheckError` are deprecated and scheduled for removal in the next
major version.
### CLI upgrades and bundling
Install the current global CLI with `npm i -g @nestjs/cli@latest`, then run
`nest upgrade` (alias `nest update`) from the project root. For a project-local
CLI, first run `npm i @nestjs/cli@latest @nestjs/schematics@latest`.
Use `nest upgrade --dry-run` to preview changes and manual follow-up.
Rspack is the default bundler for monorepos. Migrate deprecated `--webpack`,
`--webpackPath`, `webpack`, and `webpackConfigPath` to `--builder rspack`
and `--rspackPath` for a custom config path. Both `nest build` and `nest start`
support `--emit-declarations` with SWC, `--no-type-check`, and `--silent`.
Use `nest build --all --parallel 4` for four concurrent monorepo builds.
## Validation and HTTP quick reference
### Standard Schema validation and serialization
Pass a Standard Schema-compatible `schema` option to `@Body()`, `@Query()`,
`@Param()`, or `@RawBody()`. Register `StandardSchemaValidationPipe` to
validate and transform those arguments. OpenAPI generation can use the same
schema metadata.
```typescript
app.useGlobalPipes(new StandardSchemaValidationPipe());
```
Apply `StandardSchemaSerializerInterceptor` and supply the response schema
through `@SerializeOptions()` to validate and transform outgoing values.
In 12.2.0, handler-level `@SerializeOptions({})` keeps the controller's schema,
so response validation stays active.
`ConfigModule.forRoot()` also accepts a Standard Schema-compatible
`validationSchema`. If using Joi, upgrade to Joi 18+ and move Joi-specific
settings under `validationOptions.libraryOptions`; these merge over
`allowUnknown: true` and `abortEarly: false`.
### Route diagnostics
Set `routeConflictPolicy` to report duplicate and shadowed routes. On
order-sensitive adapters, opt into `routeResolutionStrategy: 'specificity'`
to prioritize static routes such as `me` over parameterized routes such as `:id`.
```typescript
const app = await NestFactory.create(AppModule, {
routeConflictPolicy: { duplicate: 'error', shadow: 'warn' },
routeResolutionStrategy: 'specificity',
});
```
In 12.6.3, duplicate detection follows router case sensitivity. With default
Express routing or Fastify `caseSensitive: false`, `GET /users` and
`GET /Users` are duplicates, and the duplicate-error policy stops bootstrap.
### Pipe and upload behavior
`ParseEnumPipe` excludes reverse mappings for numeric enums. In 12.6.1 it
checks exact matches before numeric coercion: for
`enum Status { Numeric = 0, Text = '0' }`, passing `'0'` returns the string member.
A string `fileType` treats regex metacharacters literally. Starting in 12.2.0
and 11.2.8, it must match through the end of the detected type, so `'font/woff'`
rejects `'font/woff2'`. Use a `RegExp` to accept both. The platform reference
details upload limits, storage overrides, calendar validation, and error caps.
### SSE and streamed responses
SSE handlers can use an abort signal to stop work on disconnect; pass it to
abort-aware operations started for the stream. Starting in 11.1.29, SSE comments
can keep an idle connection open without dispatching a client message, and
`retry: 0` sends an explicit zero-millisecond reconnection delay.
Use `@Sse({ maxPendingDataLength: 100_000 })` to cap queued event-data characters.
In 12.2.0, the default is 4 million characters and exceeding it disconnects the
client; `0` or `Infinity` disables the cap. The configurable cap also landed
in 11.2.8.
Starting in 12.4.0, HTTP handlers can return a Web `Response` or `ReadableStream`
directly. Starting in 12.5.0, `ClassSerializerInterceptor` and
`StandardSchemaSerializerInterceptor` process each object yielded by a streamed
HTTP response, applying exclusions and groups or a response schema to each
NDJSON record.
## Transports, gateways, and observability quick reference
### Connections and gateway setup
Microservice clients and servers expose `status`, `unwrap()`, and `on()` for
transport state, native driver access, and driver events. Transport options can
be resolved through dependency injection.
Register WebSocket adapters before application initialization. Gateways support
request-scoped providers; inject the socket with `@Inject(REQUEST)`. A gateway
in a standalone microservice needs an explicit port to listen in 12.5.0 and
11.2.10. The microservices reference gives per-transport request failure paths,
connection recovery, message limits, and graceful shutdown settings.
### Lifecycle instrumentation
Pass the `@nestjs/observe` instrument to `NestFactory.create()` to opt in to
instrumentation for HTTP, GraphQL, gRPC, microservices, queue consumers, and
cron jobs. `nest new --observe` and `nest upgrade --observe` can configure it.
```typescript
export const { ObserveModule, ObserveInstrument } = createObserveModule();
const app = await NestFactory.create(AppModule, { instrument: ObserveInstrument });
```
Add `ObserveModule.forRoot()` to the application module's `imports` and supply
the app key, secret, and service ID. In 12.6.3, testing modules accept `instrument`
as the second argument to `Test.createTestingModule()`; applications and
microservices created from the module inherit it unless they supply their own.
### Structured logging and tests
`ConsoleLogger` puts a plain object after the message into the same log entry.
JSON mode nests fields under `params`; use `flattenParams: true` for top-level
fields or `structuredParams: false` for separate records. JSON mode disables
colors by default; `colors: true` enables them for local development.
If repeated dynamic-module factory calls leave a test with multiple provider
instances, use `module.get(Target, { each: true })` to retrieve all for stubbing.
To restore metadata-based deduplication for a test, call
`Test.createTestingModule(metadata, { moduleIdGeneratorAlgorithm: 'deep-hash' })`.