Sobes.tech
Junior — Middle

Can you explain what Guards are in NestJS and how they are used for access control?

sobes.tech AI

Answer from AI

In NestJS, Guards are special classes that implement the CanActivate interface and are used to control access to routes or controller methods.

They decide whether to allow the request to proceed based on logic such as authorization checks, user roles, or other conditions.

Example of using Guards:

import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();
    return request.headers.authorization === 'valid-token';
  }
}

Then, this Guard can be applied to a controller or route:

@UseGuards(AuthGuard)
@Get('profile')
getProfile() {
  return { user: 'info' };
}

Thus, Guards allow centralized management of access to application resources.