'How to provide a Guard for a specific Module in Nest.js?

I have a module called AdminModule which should be protected by AdminGuard.

I tried to set up the Guard directly in the module like this:

@Module({
  imports: [
    HttpModule,
  ],
  controllers: [AdminController],
  providers: [
    {
      provide: APP_GUARD,
      useClass: AdminGuard,
    },
    AdminService,
  ],
})
export class AdminModule {
}

However, the guard is not limited to this module but it is global (as stated in the docs: "the guard is, in fact, global").

But how is it possible to make the guard only protect a module?



Solution 1:[1]

Update : there is actually no options to achieve that.

Information :

What you've done by using APP_GUARD is to apply it globally. It's the same as using useGlobalGuards, but this way allows you to take advantage of the DI system.

{
  provide: APP_GUARD,
  useClass: AdminGuard,
},

If you don't want to apply it globally, don't add this to the provider's array in the module.

Instead, just create a new guard like this

@Injectable()
export class RolesGuard implements CanActivate {
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    return true;
  }
}

See the documentation here: https://docs.nestjs.com/guards

And then apply it on your controller at the class level to impact all the handlers of the controller, or to a method to impact a specific endpoint.

@UseGuards(RolesGuard)

Solution 2:[2]

You can add @UseGuards(JwtAuthGuard) before the controller class,and make the guard protect all routes on the controller.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Eric Aya