nestjs-configure-after
v3.0.0
Published
Order NestJS middlewares execution
Downloads
57
Maintainers
Readme
Using NestJS?
Do you have middlewares set via configure(consuer: MiddlewareConsumer) {}
and want to control the order of execution of these middlewares?
Install
npm i nestjs-configure-after
Example
Let's assume we have ModuleA, ModuleB, and ModuleC, and each has its own middleware setup. And we want these middlewares to be set in the correct order, like A -> B -> C. By default NestJS does not provide the way to set the order. But with this library it's possible:
import { After } from 'nestjs-configure-after'
@Module({})
//
// Empty if independent
//
@After()
class ModuleA {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(FirstMiddleware)
.forRoutes('*');
}
}
@Module({})
//
// Pass module that should configure it's middlewares
// before the current one
//
@After(ModuleA)
class ModuleB {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(SecondMiddlewareThatShouldBeExecutedAfterTheFirstOne)
.forRoutes('*');
}
}
@Module({})
//
// ...Or even pass several modules
//
@After(ModuleA, ModuleB)
class ModuleC {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(TheLastMiddleware)
.forRoutes('*');
}
}
@Module({
// And for now it does not matter in which
// order modules are set in `imports` field
// Middlewares will be setup in the right order.
imports: [ModuleC, ModuleA, ModuleB, ...],
controllers: [...]
})
class App {}