Guards in NestJS | Arshnoor Singh

Guards in NestJS

As yesterday was sharing views over the guards in nest JS. Today let's find out the execution context of auth guard.

Execution Context

The canActivate() function takes a single argument, the ExecutionContext instance. The ExecutionContext inherits from ArgumentsHost.

We are just using the helper methods defined on ArgumentsHost , to get a reference to the Request object.

By extending ArgumentsHost, ExecutionContext also adds several new helper methods that provide additional details about the current execution process. These details are helpful in building more generic guards that can work across a set of execution contexts.

Binding guards

Like pipes and exception filters, guards can be controller-scoped, method-scoped, or global-scoped. Below, we can set up a controller-scoped guard using the @UseGuards() decorator.

This decorator may take a single argument, or a comma-separated list of arguments. This lets us easily apply the appropriate set of guards with one declaration.

Global guards are used across the whole application, for every controller and every route handler.

In terms of dependency injection, global guards registered from outside of any module cannot inject dependencies since this is done outside the context of any module.

Setting roles per handler

RolesGuard is working, but it's not very smart yet. We're not yet taking advantage of the most important guard feature the execution context.

It doesn't yet know about roles or which roles are allowed for each handler.