Guards in Nest JS | Arshnoor Singh

Guards in Nest JS

A guard is a class annotated with the @Injectable() decorator which implements the CanActivate interface.

Guards have a single responsibility that determine whether a given request will be handled by the route handler or not, depending on certain conditions like permissions, roles, ACLs etc. present at run-time which refers to authorization.

media

Authorization, Authentication has typically been handled by middleware in traditional Express applications.

Middleware is a fine choice for authentication since things like token validation and attaching properties to the request object are not strongly connected with a particular route context.

Middleware doesn't know which handler will be executed after calling the next() function.

On the other hand, Guards have access to the ExecutionContext instance, and thus know exactly what's going to be executed next. They're designed much like exception filters, pipes, and interceptors.

Authorization guard

Authorization is a great use case for Guards because specific routes should be available only when the caller has sufficient permissions. The AuthGuard that we build assumes an authenticated user.

It will extract and validate the token and use the extracted information to determine whether the request can proceed.

The logic inside the validateRequest() function can be as simple or sophisticated as needed. The main point of this is to show how guards fit into the request/response cycle.

Every guard must implement a canActivate() function. This function should return a boolean, indicating whether the current request is allowed or not.

It can return the response either synchronously or asynchronously. Nest uses the return value to control the next action:

  • if it returns true, the request will be processed.
  • if it returns false, Nest will deny the request.