Papooch / nestjs-cls

A continuation-local storage (async context) module compatible with NestJS's dependency injection.

Home Page:https://papooch.github.io/nestjs-cls/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cls middleware is not triggered in all routes

alexphamhp opened this issue · comments

I just got this weird error when use your library in Nestjs
I set up it in my AppModule like below :

  @Module({
    imports: [
      ClsModule.forRoot({
        global: true,
        middleware: {
          mount: true,
          generateId: true,
          idGenerator: (req: Request) =>
            req.headers[CORRELATION_ID_HEADER] ?? uuidv4(),
          setup(cls, req) {
            console.log('calling cls middleware');
            const correlationId = cls.getId();
            cls.set('correlationId', correlationId);
            req.headers[CORRELATION_ID_HEADER] = correlationId;
          },
        },
      }),
    providers: [
      {
        provide: APP_INTERCEPTOR,
        useClass: LoggingInterceptor,
      },
      {
        provide: APP_FILTER,
        useClass: AllExceptionsFilter,
      },
    ],
  })
  export class AppModule {}

In main.ts
I use prefix for API version

  app.setGlobalPrefix('api', {
      exclude: [
        {
          path: 'health',
          method: RequestMethod.GET,
        },
      ],
    });

  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      whitelist: true,
      validationError: {
        target: false,
        value: false,
      },
    })
  );
  
  app.enableVersioning({
    type: VersioningType.URI,
    defaultVersion: '1',
  });


Steps I did :

  • Get 404 route without the prefix /api/v1 => Cls Middleware is not triggered ~ there is no log "calling cls middleware"

But when I use that prefix, I see the log and also the correlationId is set in my exception response 😅
It seems like the mount: true does not work like it is supposed to do 🤔

The middleware is mounted to "*" internally with the mount: true and maybe happens too late in the process when both prefix and versioning are involved. I must admit that I haven't tested the library with versioning.

Could you test with mounting the middleware manually, or using the interceptor instead?

If you can, please provide me with a repository with a minimal reproduction of the issue that I can inspect locally.

Thanks @Papooch for the quick reply
Yes, I fixed it by using your mounting the middleware manually
I put the middleware in my bootstrap function and it worked

I agree that the mounting middleware happens too late in the process when both prefix and versioning are involved

I'm sorry, what I can public is just that above sample code 😅

Thanks for the confirmation, I've added a short note about it to the docs.