NestJS Logo

Guards

Microservice guards work the same way as regular HTTP application guards. The only difference is that they should throw RpcException instead of HttpException. When a guard returns false, Nest throws an RpcException with the Forbidden resource message.

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

Binding guards#

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

JS TS

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

@UseGuards(AuthGuard)
@MessagePattern({ cmd: 'sum' })
accumulate(data) {
  return (data || []).reduce((a, b) => a + b);
}
Hint Global guards registered on the main HTTP application don't apply to microservices connected to a hybrid application unless you set the inheritAppConfig option. See sharing configuration.
Edit on GitHub

Support us

Nest is an MIT-licensed open source project. It can grow thanks to the support of these awesome people. If you'd like to join them, please read more here.

Principal Sponsors

SerpApi LogoTrilon LogoMojam Logo

Sponsors / Partners

Become a sponsor