NestJS & @cqrs-ddd: Integrating or Migrating
Teams using NestJS have two architectural choices when adopting @cqrs-ddd:
- Keep NestJS and add the adapter
@cqrs-ddd/nestjs: Keep your existing@nestjs/cqrshandlers, buses, modules, dependency injection, and controllers. The adapter wraps handlers in behavior pipelines, provides global exception filtering, and manages correlation and job context. Nothing is replaced. - Move to framework-free CQRS with
@cqrs-ddd/cqrs: Build applications without NestJS on plain Node.js, Fastify, or Express, constructing handlers withnewand registering them oncreateCqrs(). It covers handlers and buses, not every feature of@nestjs/cqrs: see What Is Not Included.
The two are independent. An existing NestJS application takes the first and never needs the second. An application on the @nestjs-pipeline/* 0.4.x packages starts with From @nestjs-pipeline 0.4.x.
Architectural Comparison
Section titled “Architectural Comparison”| Dimension | Raw @nestjs/cqrs |
NestJS + @cqrs-ddd/nestjs |
Framework-Free @cqrs-ddd/cqrs |
|---|---|---|---|
| Handler Decorators | @CommandHandler, @QueryHandler, @EventsHandler |
Same @nestjs/cqrs decorators + @UsePipeline, @SkipPipeline |
Same names, from @cqrs-ddd/cqrs + @UsePipeline, @SkipPipeline |
| Buses | CommandBus, QueryBus, EventBus |
Same @nestjs/cqrs buses |
Same bus names, from createCqrs() |
| Pipeline Behaviors | None (requires Nest interceptors) | Compiles and executes @cqrs-ddd/pipeline around handlers |
Compiles and executes @cqrs-ddd/pipeline around handlers |
| DI & Containers | NestJS IoC container | NestJS IoC container injects behaviors and handlers | No container: explicit new in composition root |
| Exception Handling | Manual exception filters | Automatic ErrorFilter mapping package errors to HttpException |
Framework-neutral: HTTP layer maps errors (e.g. domainErrorHttpStatus) |
| Startup Diagnostics | Silent overrides on duplicates | Validates singleton scope, provider uniqueness, behavior contracts | Fails on duplicate handlers, missing decorators, contract violations |
| Runtime | NestJS | NestJS | No framework: the buses and the pipelines only |
Option 1: Integrating with NestJS via @cqrs-ddd/nestjs
Section titled “Option 1: Integrating with NestJS via @cqrs-ddd/nestjs”If you are already running on NestJS or want Nest’s dependency injection and controller ecosystem, install @cqrs-ddd/nestjs.
What You Keep
Section titled “What You Keep”- All
@Module(),@Injectable(),@Controller()definitions. - Official
@nestjs/cqrsimports:CqrsModule,CommandBus,QueryBus,EventBus,@CommandHandler,@QueryHandler,@EventsHandler. - Handlers implement
ICommandHandler,IQueryHandler,IEventHandler. - Controllers inject
CommandBusandQueryBusas usual.
What You Add
Section titled “What You Add”Minimal Setup is a complete root module with every import and provider, run by a test. The steps below show its parts.
-
PipelineModule.forRoot()inAppModule: -
Pipeline declarations on handlers:
Each behavior a handler names is a provider of a module: here
ZodValidationBehavior, andIdempotencyBehaviorbuilt with its store. -
Domain Event publication: Subclass
CommandBaseHandlerfrom@cqrs-ddd/core/applicationand pass the injected@nestjs/cqrsEventBus. Whenhandle(command)returns anAggregateRoot, uncommitted domain events are automatically published througheventBus.publishAll()and uncommitted. Delivery stays what thatEventBusprovides: the adapter adds no durable messaging and no outbox.
Option 2: Migrating off NestJS to @cqrs-ddd/cqrs
Section titled “Option 2: Migrating off NestJS to @cqrs-ddd/cqrs”If your goal is to drop NestJS for a framework-free architecture on plain Node.js, Express or Fastify, use @cqrs-ddd/cqrs.
What Carries Over
Section titled “What Carries Over”The handler decorators, the handler interfaces and the bus names match @nestjs/cqrs:
@nestjs/cqrs |
@cqrs-ddd/cqrs |
|---|---|
@CommandHandler(Command) |
@CommandHandler(Command) from @cqrs-ddd/cqrs |
@QueryHandler(Query) |
@QueryHandler(Query) from @cqrs-ddd/cqrs |
@EventsHandler(...Events) |
@EventsHandler(...Events) from @cqrs-ddd/cqrs |
ICommandHandler<TCommand> |
ICommandHandler<TCommand> from @cqrs-ddd/cqrs |
IQueryHandler<TQuery> |
IQueryHandler<TQuery> from @cqrs-ddd/cqrs |
IEventHandler<TEvent> |
IEventHandler<TEvent> from @cqrs-ddd/cqrs |
CommandBus, QueryBus, EventBus |
Returned by createCqrs() |
What Is Not Included
Section titled “What Is Not Included”@cqrs-ddd/cqrs does not replace every feature of @nestjs/cqrs. It has no sagas, no ofType RxJS pipes, no AsyncContext and no EventPublisher merge mechanisms; aggregates publish events through CommandBaseHandler. Its EventBus delivers in process: it is not durable messaging and not an outbox. An application that relies on one of these keeps NestJS and takes Option 1.
What the Application Does Itself
Section titled “What the Application Does Itself”| NestJS Responsibility | @cqrs-ddd Equivalent |
|---|---|
@Module(), @Injectable(), providers |
A plain composition function that constructs dependencies with new |
NestFactory.create(AppModule) |
const cqrs = createCqrs(options); cqrs.register(...handlers); |
| Application shutdown hooks | await cqrs.close(), then closing database pools and redis connections |
| Controllers, guards, interceptors, pipes | Native HTTP routes and middleware; see HTTP with Express and Fastify |
Request-scoped providers (Scope.REQUEST) |
AsyncLocalStorage via context sources (tenantId, correlationId) |
Complete Plain Node.js Example
Section titled “Complete Plain Node.js Example”Differences in Runtime Behavior
Section titled “Differences in Runtime Behavior”- Strict handler registration: Registering a second handler for the same command or query fails immediately in
cqrs.register(). NestJS silently overrides earlier handlers with the last one registered. - Async missing handler errors: In
@cqrs-ddd/cqrs,commandBus.execute()andqueryBus.execute()reject asynchronously withCommandHandlerNotFoundExceptionorQueryHandlerNotFoundException.@nestjs/cqrsthrows synchronously. - Graceful shutdown:
cqrs.close()awaits all running asynchronous event handlers before resolving. In NestJS,app.close()does not track background event handler completion. - Event error isolation: As in
@nestjs/cqrs, an event handler’s failure goes to theUnhandledExceptionBusand the handler keeps receiving later events;@cqrs-ddd/cqrsalso logs it, or rethrows it withrethrowUnhandled: true.
Choosing Between the Two
Section titled “Choosing Between the Two”- Choose Option 1 (
@cqrs-ddd/nestjs) when working in an existing NestJS codebase, using NestJS microservices or GraphQL, or relying heavily on Nest’s controller ecosystem and DI modules. - Choose Option 2 (
@cqrs-ddd/cqrs) when building a new service on plain Node.js, Express or Fastify, or when you want explicit construction without a dependency-injection container and none of the features listed under What Is Not Included.