Bird
Raised Fist0
NestJSframework~20 mins

Combining multiple guards in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Guard Mastery in NestJS
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when multiple guards are applied to a NestJS route?

Consider a NestJS controller method protected by two guards: AuthGuard and RolesGuard. What is the behavior when both guards are applied?

NestJS
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from './auth.guard';
import { RolesGuard } from './roles.guard';

@Controller('items')
export class ItemsController {
  @Get()
  @UseGuards(AuthGuard, RolesGuard)
  findAll() {
    return 'Items list';
  }
}
ABoth guards run in parallel; the request is allowed if either guard returns true.
BBoth guards run in the order declared; if any guard returns false, the request is denied.
COnly the first guard runs; the second guard is ignored.
DGuards run randomly; the request is allowed only if the last guard returns true.
Attempts:
2 left
💡 Hint

Think about how NestJS processes multiple guards in sequence.

📝 Syntax
intermediate
1:30remaining
Which code correctly applies multiple guards to a NestJS route?

Choose the correct syntax to apply AuthGuard and RolesGuard to a controller method.

A
@UseGuards(AuthGuard || RolesGuard)
getData() { return 'data'; }
B
@UseGuards([AuthGuard, RolesGuard])
getData() { return 'data'; }
C
@UseGuards(AuthGuard && RolesGuard)
getData() { return 'data'; }
D
@UseGuards(AuthGuard, RolesGuard)
getData() { return 'data'; }
Attempts:
2 left
💡 Hint

Remember the decorator syntax for multiple guards.

❓ state_output
advanced
2:00remaining
What is the output when the first guard denies access?

Given two guards AuthGuard and RolesGuard applied to a route, if AuthGuard returns false, what happens?

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

class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    return false; // denies access
  }
}

class RolesGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    console.log('RolesGuard checked');
    return true;
  }
}

// Route uses @UseGuards(AuthGuard, RolesGuard)
ARequest is denied immediately; RolesGuard is not executed.
BRequest is allowed because RolesGuard returns true.
CRequest is denied after both guards run.
DRequest causes a runtime error because of conflicting guards.
Attempts:
2 left
💡 Hint

Consider the guard execution order and short-circuit behavior.

🔧 Debug
advanced
1:30remaining
Why does this combined guard setup apply only one guard?

Examine the following code snippet. Why does it apply only RolesGuard instead of both?

NestJS
import { UseGuards } from '@nestjs/common';

@UseGuards(AuthGuard && RolesGuard)
getData() {
  return 'data';
}
AUsing logical AND (&&) between guard classes evaluates to the last truthy class instead of both.
BGuards must be instantiated before use; classes alone cause errors.
CMissing parentheses around guards causes a syntax error.
DThe guards are applied correctly; error is unrelated.
Attempts:
2 left
💡 Hint

Check how decorators expect arguments.

🧠 Conceptual
expert
2:30remaining
How does NestJS handle asynchronous guards when combined?

When multiple guards return Promise<boolean> (are async), how does NestJS process them?

ANestJS does not support async guards; it throws an error.
BNestJS runs all guards in parallel and allows access if any resolves to true.
CNestJS awaits each guard in order; if any resolves to false, it stops and denies access.
DNestJS runs guards sequentially but ignores their resolved values.
Attempts:
2 left
💡 Hint

Think about how async functions and promises work in sequence.

Practice

(1/5)
1.

What happens when you use @UseGuards(AuthGuard, RolesGuard) on a NestJS route handler?

Choose the best description.

easy
A. Only AuthGuard is checked; RolesGuard is ignored.
B. Both AuthGuard and RolesGuard must allow access for the request to proceed.
C. Either AuthGuard or RolesGuard allowing access is enough to proceed.
D. Guards run in parallel but only the first to approve grants access.

Solution

  1. Step 1: Understand how multiple guards work in NestJS

    When multiple guards are used with @UseGuards(), NestJS runs them in sequence and requires all to approve access.
  2. Step 2: Apply this to the given guards

    Both AuthGuard and RolesGuard must return true for the request to proceed.
  3. Final Answer:

    Both AuthGuard and RolesGuard must allow access for the request to proceed. -> Option B
  4. Quick Check:

    All guards must approve = A [OK]
Hint: All guards must pass for access, not just one [OK]
Common Mistakes:
  • Thinking only one guard needs to pass
  • Assuming guards run in parallel and race
  • Believing guards are ignored if one fails
2.

Which of the following is the correct syntax to apply two guards AuthGuard and RolesGuard on a controller method?

?
easy
A. @UseGuards(AuthGuard && RolesGuard) handleRequest() {}
B. @UseGuards(AuthGuard RolesGuard) handleRequest() {}
C. @UseGuards(AuthGuard || RolesGuard) handleRequest() {}
D. @UseGuards(AuthGuard, RolesGuard) handleRequest() {}

Solution

  1. Step 1: Recall the correct syntax for multiple guards

    In NestJS, multiple guards are passed as separate arguments to @UseGuards(), separated by commas.
  2. Step 2: Check each option

    @UseGuards(AuthGuard, RolesGuard) handleRequest() {} correctly uses comma-separated guards. @UseGuards(AuthGuard RolesGuard) handleRequest() {} misses the comma between guards, causing a syntax error. Using && or || evaluates to only one guard.
  3. Final Answer:

    @UseGuards(AuthGuard, RolesGuard) handleRequest() {} -> Option D
  4. Quick Check:

    Comma-separated guards = C [OK]
Hint: Use commas to separate guards, avoid logical operators or missing commas in @UseGuards() [OK]
Common Mistakes:
  • Omitting comma between guards
  • Using && or || inside @UseGuards()
  • Forgetting to separate guards by commas
3.

Given the following code snippet, what will be the output when a request is made?

@UseGuards(AuthGuard, RolesGuard)
@Get('profile')
getProfile() {
  return 'User Profile';
}

// AuthGuard returns true
// RolesGuard returns false
medium
A. Throws an UnauthorizedException
B. Returns 'User Profile'
C. Returns null
D. Returns an empty string

Solution

  1. Step 1: Understand guard return values effect

    Guards must all return true to allow access. If any guard returns false, NestJS throws an UnauthorizedException by default.
  2. Step 2: Apply given guard results

    Here, AuthGuard returns true but RolesGuard returns false, so access is denied and an exception is thrown.
  3. Final Answer:

    Throws an UnauthorizedException -> Option A
  4. Quick Check:

    Any guard false = UnauthorizedException [OK]
Hint: All guards must return true; one false blocks access [OK]
Common Mistakes:
  • Assuming one guard false still allows access
  • Expecting null or empty string instead of exception
  • Confusing guard return values with response data
4.

Identify the error in this NestJS controller snippet using multiple guards:

@UseGuards(AuthGuard RolesGuard)
@Get('data')
getData() {
  return 'Data';
}
medium
A. The @Get decorator is misplaced
B. Guards must be passed as an array
C. Missing comma between guards in @UseGuards()
D. Guards cannot be combined on the same method

Solution

  1. Step 1: Check syntax of @UseGuards()

    The guards inside @UseGuards() must be separated by commas.
  2. Step 2: Identify the error in the snippet

    The snippet misses a comma between AuthGuard and RolesGuard, causing a syntax error.
  3. Final Answer:

    Missing comma between guards in @UseGuards() -> Option C
  4. Quick Check:

    Comma missing between guards = D [OK]
Hint: Check commas between guards inside @UseGuards() [OK]
Common Mistakes:
  • Forgetting commas between guards
  • Passing guards as an array incorrectly
  • Misplacing decorators order
5.

You want to protect a route so that only authenticated users with the role 'admin' can access it. You have AuthGuard and RolesGuard available. How should you combine them in your controller method?

hard
A. @UseGuards(AuthGuard, RolesGuard) // RolesGuard checks for 'admin' role
B. @UseGuards(RolesGuard, AuthGuard) // Order does not matter
C. @UseGuards(AuthGuard || RolesGuard) // Either guard allows access
D. @UseGuards([RolesGuard, AuthGuard]) // Guards passed as array

Solution

  1. Step 1: Understand guard order and combination

    Guards are combined by passing them comma-separated in @UseGuards(). Order matters: AuthGuard first authenticates and sets req.user, then RolesGuard checks the role.
  2. Step 2: Choose correct syntax and logic

    @UseGuards(AuthGuard, RolesGuard) // RolesGuard checks for 'admin' role uses correct syntax, order, and notes the role check. Reversing to RolesGuard first fails as no user is set, and claims order irrelevant which is misleading. Array with reversed order fails similarly. Logical operators pass only one guard.
  3. Final Answer:

    @UseGuards(AuthGuard, RolesGuard) // RolesGuard checks for 'admin' role -> Option A
  4. Quick Check:

    Comma-separated guards with role check = B [OK]
Hint: Use comma-separated guards; RolesGuard checks roles [OK]
Common Mistakes:
  • Using logical operators inside @UseGuards()
  • Passing guards as an array
  • Assuming guard order always matters
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