Using an Interceptor
Another place to initiate the CLS context is an ClsInterceptor
, which, unlike the ClsGuard
uses AsyncLocalStorage#run
method to wrap the following code, which is considered safer than enterWith
.
To use it, pass its configuration to the interceptor
property to the ClsModule.forRoot()
options:
Automatically
app.module.ts
@Module({
imports: [
ClsModule.forRoot({
interceptor: { mount: true },
}),
],
// ...
})
export class AppModule {}
Manually
Or mount it manually as APP_INTERCEPTOR
app.module.ts
@Module({
imports: [
ClsModule.forRoot({
interceptor: { mount: false }
}),
]
providers: [
{
provide: APP_INTERCEPTOR,
useClass: ClsInterceptor,
},
],
// ...
})
export class AppModule {}
or directly on the Controller/Resolver with:
@UseInterceptors(ClsInterceptor);
note
Please note: Since Nest's Interceptors run after Guards, that means using this method makes CLS unavailable in Guards (and in case of REST Controllers, also in Exception Filters).