Guards in NestJS decide if a request can continue to the route handler by returning true or false. They are mainly used for authorization and access control.
If a guard returns false, NestJS stops processing the request and sends a 403 Forbidden response by default.
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; @Injectable() export class AdminGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); const user = request.user; // Check user role return ???; } }
Option A uses optional chaining to safely access user.role and strict equality to compare with 'admin'.
Option A uses assignment (=) instead of comparison (===), which is wrong.
Option A uses loose equality (==), which is less safe.
Option A misses quotes around 'admin', causing a ReferenceError.
Throwing ForbiddenException causes NestJS to send a 403 Forbidden response with the provided message.
The if block contains 'true;' but does not return it. So the function always returns false, blocking all access.