Bird
Raised Fist0
NestJSframework~20 mins

Guard interface (canActivate) in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 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 does this guard do when canActivate returns false?
Consider a NestJS guard where the canActivate method returns false. What happens to the request?
NestJS
import { CanActivate, ExecutionContext } from '@nestjs/common';

export class SampleGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    return false;
  }
}
AThe request is blocked and a 403 Forbidden response is sent.
BThe request proceeds to the route handler normally.
CThe request causes a server error and crashes the app.
DThe request is redirected to the login page automatically.
Attempts:
2 left
💡 Hint
Think about what returning false from a guard means in NestJS.
📝 Syntax
intermediate
2:00remaining
Which option correctly implements canActivate to allow only requests with a header 'x-api-key' equal to 'secret'?
Choose the correct implementation of canActivate that checks if the request header x-api-key equals secret.
A
canActivate(context: ExecutionContext): boolean {
  const request = context.getRequest();
  return request.headers['x-api-key'] === 'secret';
}
B
canActivate(context: ExecutionContext): boolean {
  const request = context.switchToHttp().getRequest();
  return request.header('x-api-key') === 'secret';
}
C
canActivate(context: ExecutionContext): boolean {
  const request = context.switchToHttp().getRequest();
  return request.headers['x-api-key'] === 'secret';
}
D
canActivate(context: ExecutionContext): boolean {
  const request = context.switchToHttp().getRequest();
  return request.headers.xApiKey === 'secret';
}
Attempts:
2 left
💡 Hint
Use the correct method to get the HTTP request and access headers as an object.
❓ state_output
advanced
2:00remaining
What is the output when canActivate returns a Promise resolving to false?
If canActivate returns Promise.resolve(false), what does NestJS do with the request?
NestJS
import { CanActivate, ExecutionContext } from '@nestjs/common';

export class AsyncGuard implements CanActivate {
  canActivate(context: ExecutionContext): Promise<boolean> {
    return Promise.resolve(false);
  }
}
AThe request is delayed indefinitely and times out.
BThe request proceeds to the route handler normally.
CThe request causes a runtime error because canActivate must return boolean synchronously.
DThe request is blocked and a 403 Forbidden response is sent.
Attempts:
2 left
💡 Hint
NestJS supports async guards returning Promise.
🔧 Debug
advanced
2:00remaining
Why does this guard always allow requests even when it should block some?
Identify the bug in this guard code that causes it to always allow requests.
NestJS
import { CanActivate, ExecutionContext } from '@nestjs/common';

export class BuggyGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    if (request.headers['authorization']) {
      true;
    }
    return true;
  }
}
AThe if block does not return false when authorization header is missing, so it always returns true.
BThe guard throws a syntax error because of missing return in the if block.
CThe guard returns false always because the if block is ignored.
DThe guard returns undefined causing a runtime error.
Attempts:
2 left
💡 Hint
Look carefully at the if block and what it returns.
🧠 Conceptual
expert
2:00remaining
Which statement about canActivate guards is true?
Select the true statement about the behavior of multiple guards applied to a single route in NestJS.
AAll guards run in parallel and the request proceeds if any guard returns true.
BGuards run sequentially and the request proceeds only if all guards return true.
COnly the first guard runs and its result decides the request outcome.
DGuards run after the route handler executes to validate the response.
Attempts:
2 left
💡 Hint
Think about how multiple guards combine their results.

Practice

(1/5)
1. What is the main purpose of the canActivate method in a NestJS guard?
easy
A. To format the response data
B. To handle database connections
C. To decide if a request should be allowed or denied access
D. To log user activity

Solution

  1. Step 1: Understand the role of guards in NestJS

    Guards are used to control access to routes by allowing or denying requests.
  2. Step 2: Identify the function of canActivate

    The canActivate method returns true or false to allow or deny access.
  3. Final Answer:

    To decide if a request should be allowed or denied access -> Option C
  4. Quick Check:

    Guard access control = canActivate returns true/false [OK]
Hint: Remember: canActivate returns true to allow access [OK]
Common Mistakes:
  • Confusing canActivate with response formatting
  • Thinking canActivate handles database logic
  • Assuming canActivate logs user actions
2. Which of the following is the correct syntax to implement a guard class with canActivate in NestJS?
easy
A. class MyGuard { canActivate(context) { return true; } }
B. function MyGuard() { canActivate() { return true; } }
C. const MyGuard = () => { canActivate() { return true; } }
D. class MyGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { return true; } }

Solution

  1. Step 1: Recognize the NestJS guard pattern

    Guards are classes that implement the CanActivate interface.
  2. Step 2: Check the method signature and class syntax

    The method must be named canActivate and accept an ExecutionContext parameter, returning a boolean.
  3. Final Answer:

    class MyGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { return true; } } -> Option D
  4. Quick Check:

    Guard class implements CanActivate with canActivate method [OK]
Hint: Use class with implements CanActivate and proper method signature [OK]
Common Mistakes:
  • Using function instead of class
  • Missing implements CanActivate
  • Incorrect method parameters or return type
3. Given this guard code, what will be the result when a request is made?
class AlwaysDenyGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    return false;
  }
}
medium
A. The request is denied access
B. The request is allowed to proceed
C. A runtime error occurs
D. The guard is ignored and request proceeds

Solution

  1. Step 1: Analyze the canActivate return value

    The method always returns false, meaning access is denied.
  2. Step 2: Understand guard effect on request

    When canActivate returns false, NestJS blocks the request from continuing.
  3. Final Answer:

    The request is denied access -> Option A
  4. Quick Check:

    canActivate false = deny request [OK]
Hint: False return in canActivate means deny access [OK]
Common Mistakes:
  • Assuming false allows access
  • Thinking guard causes error on false
  • Believing guard is skipped if false
4. Identify the error in this guard implementation:
class MyGuard implements CanActivate {
  canActivate() {
    return true;
  }
}
medium
A. Incorrect return type for canActivate
B. Missing parameter in canActivate method
C. Class does not implement CanActivate interface
D. canActivate method should be async

Solution

  1. Step 1: Check method signature requirements

    The canActivate method must accept a parameter of type ExecutionContext.
  2. Step 2: Compare with given code

    The method has no parameters, which breaks the interface contract.
  3. Final Answer:

    Missing parameter in canActivate method -> Option B
  4. Quick Check:

    canActivate needs ExecutionContext parameter [OK]
Hint: canActivate always needs ExecutionContext parameter [OK]
Common Mistakes:
  • Omitting method parameters
  • Assuming async is required
  • Ignoring interface implementation rules
5. You want to create a guard that only allows access if the user role is 'admin'. Which of these canActivate implementations correctly checks the role from the request object?
hard
A. canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); return request.user?.role === 'admin'; }
B. canActivate(context: ExecutionContext): boolean { const user = context.getUser(); return user.role === 'admin'; }
C. canActivate(context: ExecutionContext): boolean { const request = context.getRequest(); return request.user.role === 'admin'; }
D. canActivate(context: ExecutionContext): boolean { const req = context.switchToHttp().getRequest(); return req.user.role == 'admin'; }

Solution

  1. Step 1: Access the HTTP request correctly

    Use context.switchToHttp().getRequest() to get the request object.
  2. Step 2: Safely check the user role

    Use optional chaining request.user?.role to avoid errors if user is undefined.
  3. Final Answer:

    canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); return request.user?.role === 'admin'; } -> Option A
  4. Quick Check:

    Use switchToHttp and optional chaining for safe role check [OK]
Hint: Use switchToHttp().getRequest() and optional chaining for safety [OK]
Common Mistakes:
  • Using context.getUser() which does not exist
  • Calling context.getRequest() directly without switchToHttp()
  • Not using optional chaining causing runtime errors
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard