Guards help protect parts of your app by checking if a user can access them. Combining multiple guards lets you add more than one check easily.
Combining multiple guards in NestJS
import { UseGuards } from '@nestjs/common'; @UseGuards(FirstGuard, SecondGuard) export class SomeController { // your routes here }
You list multiple guards inside @UseGuards() separated by commas.
All guards must return true for access to be allowed.
ProfileController with two guards: one for authentication and one for roles.import { UseGuards, Controller, Get } from '@nestjs/common'; import { AuthGuard } from './auth.guard'; import { RolesGuard } from './roles.guard'; @Controller('profile') @UseGuards(AuthGuard, RolesGuard) export class ProfileController { @Get() getProfile() { return 'User profile data'; } }
getDashboard route, checking JWT and if the user is active.import { UseGuards, Get, Controller } from '@nestjs/common'; import { JwtGuard } from './jwt.guard'; import { ActiveUserGuard } from './active-user.guard'; @Controller('dashboard') export class DashboardController { @Get() @UseGuards(JwtGuard, ActiveUserGuard) getDashboard() { return 'Dashboard content'; } }
This example shows a controller protected by two guards. Both must allow access for the route to work.
import { Injectable, CanActivate, ExecutionContext, Controller, Get, UseGuards } from '@nestjs/common'; @Injectable() class AuthGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { // Simulate user is authenticated return true; } } @Injectable() class RoleGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { // Simulate user has role return true; } } @Controller('secure') @UseGuards(AuthGuard, RoleGuard) export class SecureController { @Get() getSecureData() { return 'Access granted to secure data'; } }
Guards run in the order you list them inside @UseGuards().
If any guard returns false, access is denied immediately.
You can apply guards at the controller level or on individual routes.
Use @UseGuards() with multiple guards separated by commas to combine checks.
All guards must approve access for the user to proceed.
Combining guards helps keep your code clean and reusable.
Practice
What happens when you use @UseGuards(AuthGuard, RolesGuard) on a NestJS route handler?
Choose the best description.
Solution
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.Step 2: Apply this to the given guards
BothAuthGuardandRolesGuardmust return true for the request to proceed.Final Answer:
Both AuthGuard and RolesGuard must allow access for the request to proceed. -> Option BQuick Check:
All guards must approve = A [OK]
- Thinking only one guard needs to pass
- Assuming guards run in parallel and race
- Believing guards are ignored if one fails
Which of the following is the correct syntax to apply two guards AuthGuard and RolesGuard on a controller method?
?Solution
Step 1: Recall the correct syntax for multiple guards
In NestJS, multiple guards are passed as separate arguments to@UseGuards(), separated by commas.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.Final Answer:
@UseGuards(AuthGuard, RolesGuard) handleRequest() {} -> Option DQuick Check:
Comma-separated guards = C [OK]
- Omitting comma between guards
- Using && or || inside @UseGuards()
- Forgetting to separate guards by commas
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
Solution
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.Step 2: Apply given guard results
Here,AuthGuardreturns true butRolesGuardreturns false, so access is denied and an exception is thrown.Final Answer:
Throws an UnauthorizedException -> Option AQuick Check:
Any guard false = UnauthorizedException [OK]
- Assuming one guard false still allows access
- Expecting null or empty string instead of exception
- Confusing guard return values with response data
Identify the error in this NestJS controller snippet using multiple guards:
@UseGuards(AuthGuard RolesGuard)
@Get('data')
getData() {
return 'Data';
}
Solution
Step 1: Check syntax of @UseGuards()
The guards inside@UseGuards()must be separated by commas.Step 2: Identify the error in the snippet
The snippet misses a comma betweenAuthGuardandRolesGuard, causing a syntax error.Final Answer:
Missing comma between guards in @UseGuards() -> Option CQuick Check:
Comma missing between guards = D [OK]
- Forgetting commas between guards
- Passing guards as an array incorrectly
- Misplacing decorators order
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?
Solution
Step 1: Understand guard order and combination
Guards are combined by passing them comma-separated in@UseGuards(). Order matters:AuthGuardfirst authenticates and setsreq.user, thenRolesGuardchecks the role.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.Final Answer:
@UseGuards(AuthGuard, RolesGuard) // RolesGuard checks for 'admin' role -> Option AQuick Check:
Comma-separated guards with role check = B [OK]
- Using logical operators inside @UseGuards()
- Passing guards as an array
- Assuming guard order always matters
Ready to prove it?
Pass the test and this pattern moves unknown
