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)
---
name: nestjs-knowledge-patch
description: NestJS
version: "11.1.x selected changes"
license: MIT
metadata:
author: Nevaberry
---
# NestJS compatibility guidance
Use this skill when upgrading NestJS projects or working on module identity,
lifecycle hooks, configuration, HTTP routing, validation, microservice transports,
WebSocket gateways, logging, or instrumentation.
## Reference index
| Reference | Topics |
| --- | --- |
| [Modules, Lifecycle, and Configuration](references/modules-lifecycle-and-configuration.md) | Runtime requirements; CLI upgrades, scaffolding, builds, and deployment; modules, injection, lifecycle, metadata, testing, configuration, and caching |
| [Platform and Routing](references/platform-and-routing.md) | HTTP adapters, routes, middleware, versioning, errors, streams, SSE, validation, serialization, uploads, security, and GraphQL |
| [Transports and Operations](references/transports-and-operations.md) | Transport options, patterns, requests, shutdown, resource limits, WebSockets, instrumentation, logging, and health indicators |
## Breaking changes and deprecations
### Runtime and upgrade commands
Core packages ship as ESM in NestJS 12 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 schematics runtime
requirement: use Node.js 22.22.3+ on 22.x, 24.15+ on 24.x, or 26+.
Install the current 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`. The upgrade preserves the
project's CommonJS or ESM format. Use `nest upgrade --dry-run` to preview changes
and manual follow-up.
### Module identity, exports, and lifecycle
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, shutdown hooks 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 the relative ordering of providers or modules.
### Cache stores and environment validation
Replace the singular `store` setting with a `stores` array of Keyv adapters for an
external cache. Keyv stores an envelope with `value` and `expires` fields and
unwraps `value` through its API. Account for the new format when reading the
backend directly or needing entries written by the previous cache manager.
In `@nestjs/config` 4, `ConfigService.get()` checks internal configuration first,
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 from a `.env` file remain
eligible for validation.
### Express and Fastify route patterns
For Express 5, use `@Get('users/*splat')` for paths below `users` and
`forRoutes('{*splat}')` for middleware that also runs on the root path. NestJS 11
automatically converts legacy wildcard patterns.
Fastify controller routes keep their wildcard syntax. For middleware registered
through `MiddlewareConsumer`, migrate `forRoutes('(.*)')` to `forRoutes('*splat')`.
On Fastify 11.2.11, use `forRoutes('{*path}')` to include `/`; after the middie
update, `*path` matches only subpaths.
Fastify allows only CORS-safelisted methods by default. List the methods your app
needs, including any safelisted methods clients use:
```typescript
app.enableCors({ methods: ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'] });
```
### NATS, GraphQL, and event-handler migrations
For NATS v3, 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 the payload with `msg.json()`.
Migrate GraphQL subscriptions from `subscriptions-transport-ws` to `graphql-ws`
on both server and clients because the protocols are wire-incompatible. Review
`onConnect` callbacks. GraphiQL is the default IDE; replace `playground` with
`graphiql` and pass an options object to customize it.
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.
### CLI bundling and health indicators
Rspack is the default monorepo bundler. Migrate deprecated `--webpack` and
`--webpackPath` flags and the `webpack` and `webpackConfigPath` config keys to
`--builder rspack` and `--rspackPath` for a custom config path.
Inject `HealthIndicatorService` from `TerminusModule` and return
`check(key).up()` or `check(key).down()`. A down result accepts metadata or a
message string. Legacy `HealthIndicator` and `HealthCheckError` are deprecated
and scheduled for removal in the next major version.
## Request validation and response 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 metadata.
```typescript
app.useGlobalPipes(new StandardSchemaValidationPipe());
@Get(':id')
findOne(@Param('id', { schema: z.coerce.number().int().positive() }) id: number) {
return this.usersService.findOne(id);
}
```
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.
Starting in 12.5.0, `ClassSerializerInterceptor` and
`StandardSchemaSerializerInterceptor` process each object yielded by a streamed
HTTP response, applying exclusions and groups or schemas to each NDJSON record.
`ConfigModule.forRoot()` also accepts a Standard Schema-compatible
`validationSchema`. If using Joi, upgrade to Joi 18+ and move Joi-specific
settings under `validationOptions.libraryOptions`. Those options merge over
`allowUnknown: true` and `abortEarly: false`.
In 12.2.0 and 11.2.8, `ValidationPipe` caps error messages at 1,000,000 characters
by default and omits `error.target`. Configure `maxErrorMessagesLength` or pass
`validationError: { target: true }` if a custom `exceptionFactory` needs the object.
## Routing and HTTP streams
Use `routeConflictPolicy` to report duplicate and shadowed routes. On
order-sensitive adapters, `routeResolutionStrategy: 'specificity'` prioritizes
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-route 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.
Starting in 12.1.0, `setGlobalPrefix()` accepts an array of prefixes. Fastify
controller routes support HTTP `QUERY` through `RequestMethod.QUERY`.
Starting in 12.4.0, HTTP handlers can return a Web `Response` or `ReadableStream`
directly. The Node adapter provides `inject()` for HTTP tests without a listening
socket starting in 12.4.1.
SSE handlers can use an abort signal to stop work on client disconnect; pass it
to abort-aware operations started for the stream. Use
`@Sse({ maxPendingDataLength: 100_000 })` to cap queued event-data characters.
In 12.2.0 the default is 4 million characters, and Nest disconnects clients that
exceed it. Set `0` or `Infinity` to disable the cap; it also landed in 11.2.8.
## Providers, startup, and testing
If repeated dynamic-module factory calls leave multiple provider instances in a
test, retrieve all with `module.get(Target, { each: true })` for stubbing. Restore
metadata-based test deduplication with
`Test.createTestingModule(metadata, { moduleIdGeneratorAlgorithm: 'deep-hash' })`.
Lazy-loaded modules can reuse an existing singleton provider from an
already-loaded module. Nest also scans already-registered dynamic modules listed
in a lazy module's `imports`, making their exported providers injectable.
In 12.5.0 and 11.2.10, a guard, interceptor, or pipe binding that cannot run fails
bootstrap. An `@Optional()` dependency that is registered but fails to initialize
at request time fails its consumer; transient providers with durable dependencies
are built per request.
In 12.6.3, pass `instrument` as part of the second argument to
`Test.createTestingModule()`. Its `instanceDecorator` runs for providers, including
overrides. Applications and microservices created from the testing module inherit
the instrument unless they supply their own.
## Transports, logging, and instrumentation
Microservice clients and servers expose `status` to observe transport state,
`unwrap()` to access the native driver, and `on()` to listen to driver events.
Transport options can be resolved through Nest's dependency-injection container.
In 12.5.0 and 11.2.10, a TCP microservice with an empty or omitted `host` binds to
localhost. Set `options.host` to a specific interface for remote clients or use
`0.0.0.0` or `::` for all interfaces. Set `options.port` to `0` for an OS-chosen port.
In 12.6.1, a RabbitMQ server with
`options: { noAck: false, nackOnInternalError: true }` negatively acknowledges
internal handler exceptions, excluding `RpcException`, without requeueing; a
configured dead-letter exchange receives the message.
`ConsoleLogger` puts a plain object after the message in 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.
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. Add
`ObserveModule.forRoot()` to the application module's `imports` and supply the
app key, secret, and service ID.