@cqrs-ddd/nestjs
The NestJS adapter for the @cqrs-ddd packages.
A NestJS application keeps idiomatic NestJS architecture: modules, dependency injection, controllers, and official @nestjs/cqrs (CqrsModule, CommandBus, QueryBus, EventBus, @CommandHandler, @QueryHandler, @EventsHandler). The adapter provides what @nestjs/cqrs lacks:
- Pipeline behaviors around handlers: compiles and executes
@cqrs-ddd/pipelinebehaviors around every command, query, and event handler instance at application bootstrap. - Standardized exception filtering:
ErrorFilterconverts every@cqrs-ddderror (domain errors, validation failures, authorization denials, rate limits, idempotency conflicts, feature flags) into a NestJSHttpExceptionwith NestJS’s standard response body and HTTP headers. - Correlation ID propagation:
CorrelationMiddlewareruns each request with the correlation id of itsx-correlation-idheader, or a new UUIDv7, and echoes it on the response. - Asynchronous job context:
JobContextModulepropagates tenants, correlation IDs, and principals to worker queues (such as BullMQ) and restores them in processors. - Aggregate lifecycle integration: commands extending
CommandBaseHandlerpublish uncommitted aggregate domain events through the NestJSEventBus.
A complete working NestJS application demonstrating all patterns is available in the nestjs-pipeline api/ repository.
Installation
Section titled “Installation”Peer Dependencies
Section titled “Peer Dependencies”- Required peers:
@nestjs/common,@nestjs/coreand@nestjs/cqrs12, and@cqrs-ddd/pipelineand@cqrs-ddd/core0.5. NestJS itself needsreflect-metadataandrxjs. - Optional peers, installed when the application uses them:
@cqrs-ddd/pipeline-zod,@cqrs-ddd/pipeline-casl,@cqrs-ddd/pipeline-feature-flags,@cqrs-ddd/pipeline-rate-limitand@cqrs-ddd/pipeline-idempotency:ErrorFilterconverts the errors of each one installed.@cqrs-ddd/pipeline-correlation, for@cqrs-ddd/nestjs/correlation.@cqrs-ddd/pipeline-job-context, for@cqrs-ddd/nestjs/job-context.
Any other behavior package (cache, resilience, audit, telemetry, dead letters) runs in the pipelines without the adapter knowing it.
Minimal Setup
Section titled “Minimal Setup”A complete root module: the official CqrsModule, PipelineModule, a provider for each behavior that runs, and one handler. In a NestJS application, install the adapter and, for the validation, @cqrs-ddd/pipeline-zod:
Every behavior that runs is a provider: LoggingBehavior through a factory, because it takes a logger, and ZodValidationBehavior as a class. A behavior that a pipeline names and no module provides stops the application at startup. A controller, or any other provider, runs the command through the CommandBus of @nestjs/cqrs:
An invalid command rejects with ZodValidationError before the handler runs, and ErrorFilter answers it over HTTP with 400 Bad Request. This module is integration/nestjs/invoices.ts in the repository, run by its spec; integration/nestjs/app.ts is a larger application with controllers, authorization and rate limiting, tested over HTTP on Express and Fastify.
Architectural Lifecycle
Section titled “Architectural Lifecycle”The adapter operates via PipelineBootstrap, an @Injectable() service registered by PipelineModule:
Key runtime guarantees:
- Instance wrapping, not prototype mutation: Only the current application’s provider instances are wrapped. Handler class prototypes are never patched, allowing multiple isolated applications in one process.
- Fail-fast validation: Missing behavior providers, ambiguous duplicate providers, request-scoped handlers, or broken behavior contracts fail during application startup before the HTTP listener starts accepting traffic.
- Clean teardown:
OnModuleDestroyrestores original method descriptors on all wrapped handler instances.
Pipeline Configuration
Section titled “Pipeline Configuration”Import PipelineModule.forRoot() in your root module or core infrastructure module:
PipelineModuleOptions
Section titled “PipelineModuleOptions”| Option | Type | Default | Description |
|---|---|---|---|
globalBehaviors |
GlobalBehaviorsOptions | GlobalBehaviorsOptions[] |
none | Behaviors placed around handlers across defined scopes ('all', 'commands', 'queries', 'events'). |
sources |
ContextSources |
none | Where pipelines read and restore the tenantId and correlationId, such as tenantSource of @cqrs-ddd/pipeline-tenant and correlationSource of @cqrs-ddd/pipeline-correlation. |
diagnostics |
'strict' | 'warn' | 'off' |
'strict' |
Validation mode for behavior contracts: 'strict' throws PipelineConfigurationError on startup; 'warn' logs warnings; 'off' bypasses checks. |
Registering Behaviors with Dependency Injection
Section titled “Registering Behaviors with Dependency Injection”Behaviors are plain classes configured with dependencies (loggers, Redis stores, database pools, CASL loaders). Each module provides the behavior instance it configures under the behavior’s class token:
Provider Rules
Section titled “Provider Rules”- Singleton scope required: Every behavior provider and every handler running behaviors must be static singletons (
Scope.DEFAULT). If a handler or behavior is request-scoped (Scope.REQUEST),PipelineBootstrapfails startup immediately. Request-specific data must be accessed viaAsyncLocalStorageor context sources. - Single provider per behavior: Exactly one module must provide each behavior class token. If two modules register providers for the same behavior token,
PipelineBootstrapthrows an error naming both modules to prevent ambiguity.
Handlers and Declarations
Section titled “Handlers and Declarations”Command, query, and event handlers use standard @nestjs/cqrs handler decorators. Use @UsePipeline and @SkipPipeline from @cqrs-ddd/pipeline to configure behaviors:
Behavior Execution Flow
Section titled “Behavior Execution Flow”When a controller dispatches commandBus.execute(command), the call enters the compiled pipeline of CreateOrderHandler. Behaviors nest like an onion, outermost first: the global before behaviors (logging), then the handler’s own in declaration order (authorization, validation, idempotency, audit), then the global after behaviors. The handler’s execute(command) runs innermost, with the validated command. Each behavior then sees the result, or the error, on the way out: audit records the outcome, idempotency stores the response, logging writes the duration. A behavior that throws, such as a denied authorization, stops the call before the inner ones run.
Error Handling with ErrorFilter
Section titled “Error Handling with ErrorFilter”ErrorFilter intercepts all @cqrs-ddd errors and translates them into standard NestJS HttpException instances matching Nest’s default JSON error shape ({ statusCode, message, error }).
Register it globally in AppModule:
Error Translation Mapping
Section titled “Error Translation Mapping”| Error Class | Source Package | HTTP Status | Response Body Shape | Extra Headers |
|---|---|---|---|---|
ZodValidationError |
@cqrs-ddd/pipeline-zod |
400 Bad Request | { statusCode: 400, error: 'Bad Request', message: ['field: error message'] } |
— |
UnauthorizedActionException |
@cqrs-ddd/pipeline-casl |
403 Forbidden | { statusCode: 403, error: 'Forbidden', message, action, subject } |
— |
FeatureDisabledError |
@cqrs-ddd/pipeline-feature-flags |
403 Forbidden | { statusCode: 403, error: 'Forbidden', message, flag } |
— |
RateLimitExceededError |
@cqrs-ddd/pipeline-rate-limit |
429 Too Many Requests | { statusCode: 429, error: 'Too Many Requests', message, retryAfter } |
Retry-After: <seconds> |
IdempotencyConflictError |
@cqrs-ddd/pipeline-idempotency |
409 Conflict (in_progress, replay_scope) / 422 Unprocessable Entity (key_reuse) |
{ statusCode, error, message, reason } |
— |
EntityNotFoundException |
@cqrs-ddd/core |
404 Not Found | { statusCode: 404, error: 'Not Found', message: 'Order not found' } |
— |
ConcurrencyConflictError |
@cqrs-ddd/core, thrown by @cqrs-ddd/mikro-orm |
409 Conflict | { statusCode: 409, error: 'Conflict', message } |
— |
MissingTenantContextError |
@cqrs-ddd/core |
500 Internal Server Error | { statusCode: 500, error: 'Internal Server Error', message: 'Internal server error' }: a server misconfiguration, its message kept out of the answer |
— |
any other DomainException, such as InvalidValueException |
@cqrs-ddd/core or the application |
400 Bad Request | { statusCode: 400, error: 'Bad Request', message } |
— |
Unrecognized errors fall back to NestJS’s default BaseExceptionFilter handling (returning 500 Internal Server Error for unhandled exceptions).
Custom Exception Filters
Section titled “Custom Exception Filters”To handle application-specific exceptions while retaining @cqrs-ddd error conversions, extend ErrorFilter or use toHttpException and httpAnswer:
Correlation ID Middleware
Section titled “Correlation ID Middleware”CorrelationMiddleware takes the correlation id of each request from its x-correlation-id header, or generates a UUIDv7 when the header is absent or invalid, runs the request with it in AsyncLocalStorage, and sets the header on the response. It is httpCorrelation() of @cqrs-ddd/pipeline-correlation as a NestJS middleware, and works on Express and Fastify.
Register in AppModule:
Pipelines take it through sources: { correlationId: correlationSource }; read it anywhere else with getCorrelationId():
Background Jobs with JobContextModule
Section titled “Background Jobs with JobContextModule”When a request enqueues a job (BullMQ, SQS, …), the worker that runs it has none of the request’s context. JobContextModule registers a tenant list, a principal resolver, and context sources with @cqrs-ddd/pipeline-job-context:
Enqueue jobs carrying context using withJobContext, and wrap processors with @InJobContext():
Domain-Driven Design Integration
Section titled “Domain-Driven Design Integration”@cqrs-ddd/core aggregates and domain events integrate cleanly with @nestjs/cqrs.
CommandBaseHandler with NestJS EventBus
Section titled “CommandBaseHandler with NestJS EventBus”The NestJS @nestjs/cqrs EventBus implements IDomainEventPublisher (publishAll(events, dispatcherContext)). Command handlers extending CommandBaseHandler automatically publish uncommitted domain events recorded on returned aggregates:
Optimistic Concurrency and 409 Conflict
Section titled “Optimistic Concurrency and 409 Conflict”When using @PersistedWrite() on aggregate repositories, update collisions throw ConcurrencyConflictError. When dispatched via commandBus.execute(), ErrorFilter catches the error and responds with HTTP status 409 Conflict without requiring manual try/catch blocks in controllers or handlers.
Complete Production Example
Section titled “Complete Production Example”Below is an end-to-end user registration command handler in NestJS demonstrating validation, idempotency, audit logging, and domain event dispatch:
Troubleshooting & Invariants
Section titled “Troubleshooting & Invariants”Request-Scoped Handlers or Behaviors
Section titled “Request-Scoped Handlers or Behaviors”If a handler or behavior is configured with { scope: Scope.REQUEST }, application startup fails with:
Resolution: Ensure all handlers, behaviors, and their injected dependencies are singletons (Scope.DEFAULT). Read tenant IDs, user identities, or tokens from AsyncLocalStorage via pipeline sources.
Missing Behavior Provider
Section titled “Missing Behavior Provider”If a handler declares a behavior via @UsePipeline(MyBehavior) or a tuple, but no module registers a provider for MyBehavior:
Resolution: Add { provide: MyBehavior, useClass: MyBehavior } (or useFactory) to the providers and exports of the module managing that concern.
Duplicate Behavior Providers
Section titled “Duplicate Behavior Providers”If multiple modules provide the same behavior class token:
Resolution: Provide the behavior once in a dedicated shared module and export it.