Guards

There is no fundamental difference between microservices guards and regular HTTP application guards. The only difference is that instead of throwing HttpException, you should use RpcException.

Hint The RpcException class is exposed from @nestjs/microservices package.

Binding guards

The following example uses a method-scoped guard. Just as with HTTP based applications, you can also use controller-scoped guards (i.e., prefix the controller class with a @UseGuards() decorator).

  1. @UseGuards(AuthGuard)
  2. @MessagePattern({ cmd: 'sum' })
  3. accumulate(data: number[]): number {
  4. return (data || []).reduce((a, b) => a + b);
  5. }
  1. @UseGuards(AuthGuard)
  2. @MessagePattern({ cmd: 'sum' })
  3. accumulate(data) {
  4. return (data || []).reduce((a, b) => a + b);
  5. }