Bird
Raised Fist0
NestJSframework~10 mins

Protected routes with guards in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Protected routes with guards
Request to route
↓
Guard checks condition
↓
Allow
↓
Route handler executes
When a request comes in, the guard checks if access is allowed. If yes, the route runs. If no, access is denied.
Execution Sample
NestJS
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    return !!request.user;
  }
}
This guard checks if the request has a user object to allow access.
Execution Table
StepActionRequest.userGuard ResultRoute Execution
1Request arrives at protected routeundefinedCheck if user existsNo
2Guard runs canActivate()undefinedfalseBlocked, 403 returned
3Request arrives at protected route{ id: 1, name: 'Alice' }Check if user existsYes
4Guard runs canActivate(){ id: 1, name: 'Alice' }trueRoute handler runs
💡 Execution stops when guard returns false, blocking access with 403.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
request.userundefinedundefined{ id: 1, name: 'Alice' }{ id: 1, name: 'Alice' }
guard.canActivate resultN/Afalsetruetrue
Key Moments - 2 Insights
Why does the route handler not run when request.user is undefined?
Because the guard's canActivate method returns false (see execution_table step 2), blocking access before the route runs.
What does the guard check to allow access?
It checks if request.user exists and is truthy (execution_table steps 3 and 4). If yes, it returns true to allow the route.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2. What is the guard's result when request.user is undefined?
Afalse
Btrue
Cundefined
Dthrows error
💡 Hint
Check the 'Guard Result' column at step 2 in the execution_table.
At which step does the route handler run?
AStep 2
BStep 4
CStep 3
DStep 1
💡 Hint
Look at the 'Route Execution' column in the execution_table.
If request.user is always undefined, what will happen to all requests?
AAll requests are allowed
BSome requests allowed, some blocked
CAll requests are blocked
DGuard throws an error
💡 Hint
Refer to variable_tracker for request.user values and guard results.
Concept Snapshot
Protected routes use guards to check access.
Guard's canActivate returns true or false.
If true, route runs; if false, access denied (403).
Common check: request.user exists.
Guards run before route handlers.
Full Transcript
In NestJS, protected routes use guards to control access. When a request comes in, the guard's canActivate method runs. It checks if the request has a user object. If the user exists, canActivate returns true, allowing the route handler to execute. If not, it returns false, blocking access and returning a 403 error. This process ensures only authenticated users reach protected routes.

Practice

(1/5)
1. What is the main purpose of a guard in NestJS when protecting routes?
easy
A. To decide if a request can access a route based on custom logic
B. To format the response data before sending it
C. To handle database connections automatically
D. To log every request made to the server

Solution

  1. Step 1: Understand the role of guards

    Guards in NestJS are designed to control access to routes by running custom logic before the route handler executes.
  2. Step 2: Identify the correct purpose

    Among the options, only deciding if a request can access a route matches the guard's role.
  3. Final Answer:

    To decide if a request can access a route based on custom logic -> Option A
  4. Quick Check:

    Guards control access = C [OK]
Hint: Guards allow or block access before route runs [OK]
Common Mistakes:
  • Confusing guards with interceptors or middleware
  • Thinking guards modify response data
  • Assuming guards handle database tasks
2. Which of the following is the correct way to apply a guard to a route in NestJS?
easy
A. @UseGuards(AuthGuard) before the controller class
B. @UseGuards(AuthGuard) before the route handler method
C. @ApplyGuard(AuthGuard) inside the constructor
D. @Guard(AuthGuard) before the route handler

Solution

  1. Step 1: Recall the decorator for guards

    The correct decorator to apply guards in NestJS is @UseGuards().
  2. Step 2: Identify correct placement

    This decorator can be placed before a route handler method or a controller class. @UseGuards(AuthGuard) before the route handler method correctly shows it before a route handler method.
  3. Final Answer:

    @UseGuards(AuthGuard) before the route handler method -> Option B
  4. Quick Check:

    @UseGuards + route method = D [OK]
Hint: Use @UseGuards() decorator on methods or controllers [OK]
Common Mistakes:
  • Using @Guard or @ApplyGuard which don't exist
  • Placing decorators inside constructor
  • Confusing middleware with guards
3. Given this guard implementation, what will happen when a request is made?
import { CanActivate, ExecutionContext } from '@nestjs/common';

export class AlwaysDenyGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    return false;
  }
}

Applied to a route, what is the result?

medium
A. The guard throws an error causing a server crash
B. The route handler runs and returns its response
C. The request is blocked and the route handler does not run
D. The guard logs the request but allows it

Solution

  1. Step 1: Analyze the canActivate method

    The guard's canActivate method always returns false, meaning it denies access.
  2. Step 2: Understand guard effect on route

    When canActivate returns false, NestJS blocks the request and does not run the route handler.
  3. Final Answer:

    The request is blocked and the route handler does not run -> Option C
  4. Quick Check:

    canActivate false blocks request = A [OK]
Hint: canActivate false means block access [OK]
Common Mistakes:
  • Thinking false lets the route run
  • Assuming guard throws error on false
  • Confusing logging with blocking
4. 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;
    }
  }
}
medium
A. Incorrect import of ExecutionContext
B. Using switchToHttp() is not allowed in guards
C. canActivate should be async but is not
D. Missing return statement when user is not present

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<boolean>. 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]
Hint: Always return true or false in canActivate [OK]
Common Mistakes:
  • Forgetting else return false
  • Assuming undefined is false
  • Thinking async is always required
5. You want to protect a route so only users with role 'admin' can access it. Which guard implementation correctly enforces this?
import { CanActivate, ExecutionContext } from '@nestjs/common';

export class RolesGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const user = request.user;
    // Which condition correctly checks for admin role?
  }
}
hard
A. return user && user.role === 'admin';
B. return user && user.roles.includes('admin');
C. return user && user.roles === 'admin';
D. return user && user.role.includes('admin');

Solution

  1. Step 1: Understand user role structure

    Assuming user has a single role string in property role, not an array.
  2. Step 2: Check each condition

    return user && user.role === 'admin'; correctly compares user.role === 'admin'. return user && user.roles.includes('admin'); assumes roles is an array, which may be incorrect. Options C and D misuse property types.
  3. Final Answer:

    return user && user.role === 'admin'; -> Option A
  4. Quick Check:

    Check user.role string equals 'admin' = A [OK]
Hint: Match exact role property type to check admin [OK]
Common Mistakes:
  • Confusing roles array with single role string
  • Using includes on a string property
  • Checking wrong property name
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