Bird
0
0

Identify the error in this guard code snippet:

medium📝 Debug Q14 of 15
NestJS - Authentication
Identify the error in this guard code snippet:
import { CanActivate, ExecutionContext } from '@nestjs/common';

export class MyGuard implements CanActivate {
  canActivate(context: ExecutionContext) {
    if (context.switchToHttp().getRequest().user) {
      return true;
    }
  }
}
AIncorrect import of ExecutionContext
BUsing switchToHttp() is not allowed in guards
CcanActivate should be async but is not
DMissing return statement when user is not present
Step-by-Step Solution
Solution:
  1. Step 1: Check canActivate return paths

    The method returns true if user exists, but returns nothing (undefined) otherwise.
  2. Step 2: Understand guard return requirements

    canActivate must always return a boolean or Promise. Missing return means undefined, which is invalid.
  3. Final Answer:

    Missing return statement when user is not present -> Option D
  4. Quick Check:

    All paths must return boolean = B [OK]
Quick Trick: Always return true or false in canActivate [OK]
Common Mistakes:
  • Forgetting else return false
  • Assuming undefined is false
  • Thinking async is always required

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes