In nest.js while using passport module do we have to use PassportModule.register() inside each modules?

Viewed 5723

If we don't import them inside each modules using @AuthGuard decorator then it's showing the following warning in logs.

In order to use "defaultStrategy", please, ensure to import PassportModule in each place where AuthGuard() is being used. Otherwise, passport won't work correctly

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secretOrPrivateKey: 'secretKey',
      signOptions: {
        expiresIn: 3600,
      },
    }),
    UsersModule,
  ],
  providers: [AuthService, JwtStrategy],
})
export class AuthModule {}

Is there any other way besides importing "PassportModule.register({ defaultStrategy: 'jwt' })" inside each modules.

1 Answers

Assuming that your other Modules are importing the AuthModule in order to have access to the AuthService you could just re-export the PassportModule:

const passportModule = PassportModule.register({ defaultStrategy: 'jwt' });

@Module({
  imports: [
    passportModule,
    JwtModule.register({
      secretOrPrivateKey: 'secretKey',
      signOptions: {
        expiresIn: 3600,
      },
    }),
    UsersModule,
  ],
  providers: [AuthService, JwtStrategy],
  exports: [passportModule]
})
export class AuthModule {}
Related