0
0
NestJSframework~20 mins

Protected routes with guards in NestJS - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
NestJS Guard Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when a request is made to a route protected by a guard that returns false?

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?

NestJS
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';
}
AThe request is denied and the client receives a 403 Forbidden response.
BThe request proceeds and the client receives 'Protected content'.
CThe server throws an internal server error (500).
DThe guard is ignored and the route behaves as if unprotected.
Attempts:
2 left
💡 Hint

Think about what returning false from canActivate means for route access.

📝 Syntax
intermediate
2:00remaining
Which option correctly implements a guard that allows access only if a request header 'x-api-key' equals 'secret'?

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.

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

@Injectable()
export class ApiKeyGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    return request.headers.xApiKey === 'secret';
  }
}
B
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';

@Injectable()
export class ApiKeyGuard implements CanActivate {
  canActivate(context: ExecutionContext) {
    const request = context.switchToHttp().getRequest();
    if (request.headers['x-api-key'] === 'secret') {
      return true;
    }
    return false;
  }
}
C
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';

@Injectable()
export class ApiKeyGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    return request.headers['X-API-KEY'] === 'secret';
  }
}
D
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';

@Injectable()
export class ApiKeyGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    return request.headers['x-api-key'] === 'secret';
  }
}
Attempts:
2 left
💡 Hint

Remember that HTTP headers are case-insensitive but usually accessed in lowercase in Node.js.

🔧 Debug
advanced
2:00remaining
Why does this guard always allow access even when the token is missing?

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?

NestJS
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;
  }
}
AThe guard throws a syntax error due to missing return in the if block.
BThe guard returns undefined causing NestJS to allow access by default.
CThe guard always returns true because the if block does not return false explicitly.
DThe guard returns false but the route is still accessible due to misconfiguration.
Attempts:
2 left
💡 Hint

Look carefully at the if block and what it returns.

state_output
advanced
2:00remaining
What is the output when a guard throws an exception inside canActivate?

Consider a guard that throws a ForbiddenException inside its canActivate method. What will the client receive when accessing the protected route?

NestJS
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';
}
AThe client receives a 403 Forbidden response with message 'Access denied'.
BThe client receives a 500 Internal Server Error response.
CThe client receives 'Secret data' because exceptions are ignored.
DThe server crashes and stops responding.
Attempts:
2 left
💡 Hint

Think about how NestJS handles exceptions thrown in guards.

🧠 Conceptual
expert
2:00remaining
Which statement about NestJS guards and route protection is TRUE?

Choose the correct statement about how NestJS guards protect routes.

AGuards run after route handlers and can modify the response before sending.
BMultiple guards can be applied to a route and all must return true to allow access.
CGuards can only be applied at the controller level, not on individual routes.
DIf a guard returns a Promise that resolves to false, NestJS treats it as true.
Attempts:
2 left
💡 Hint

Consider how multiple guards work together in NestJS.