Consider a NestJS route protected by a guard. The guard's canActivate method returns false. What will be the result when a client tries to access this route?
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'; @Injectable() export class AuthGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { return false; } } // Controller snippet @Get('protected') @UseGuards(AuthGuard) getProtected() { return 'Protected content'; }
Think about what returning false from canActivate means for route access.
When a guard's canActivate method returns false, NestJS denies access to the route and responds with a 403 Forbidden status. This prevents the route handler from executing.
Choose the correct NestJS guard implementation that checks if the request header x-api-key equals secret. If it matches, access is allowed; otherwise, denied.
Remember that HTTP headers are case-insensitive but usually accessed in lowercase in Node.js.
Option D correctly accesses the header in lowercase and compares it to 'secret'. Option D uses assignment instead of comparison. Option D uses camelCase which is incorrect for headers. Option D uses uppercase keys which may not match the actual header key in Node.js.
Examine the following guard code. It is intended to deny access if the authorization header is missing. However, it always allows access. What is the cause?
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'; @Injectable() export class TokenGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); if (!request.headers.authorization) { return false; } return true; } }
Look carefully at the if block and what it returns.
The if block contains true; but does not return it. The function always returns true at the end, so access is always allowed.
Consider a guard that throws a ForbiddenException inside its canActivate method. What will the client receive when accessing the protected route?
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common'; @Injectable() export class ExceptionGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { throw new ForbiddenException('Access denied'); } } // Controller snippet @Get('secret') @UseGuards(ExceptionGuard) getSecret() { return 'Secret data'; }
Think about how NestJS handles exceptions thrown in guards.
When a guard throws a ForbiddenException, NestJS catches it and sends a 403 Forbidden response with the provided message.
Choose the correct statement about how NestJS guards protect routes.
Consider how multiple guards work together in NestJS.
In NestJS, multiple guards can be applied to a route. All guards must return true (or resolve to true) for access to be granted. Guards run before the route handler. Guards can be applied at both controller and route levels. If a guard returns a Promise resolving to false, access is denied.