0
0
NestJSframework~10 mins

Protected routes with guards in NestJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the guard decorator in NestJS.

NestJS
import { [1] } from '@nestjs/common';
Drag options to blanks, or click blank then click option'
AUseGuards
BController
CInjectable
DModule
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Controller instead of UseGuards
Using Injectable which is for services
Trying to import Module which is unrelated here
2fill in blank
medium

Complete the code to apply a guard to a route handler.

NestJS
@UseGuards([1])
@Get('profile')
getProfile() {
  return 'User profile';
}
Drag options to blanks, or click blank then click option'
AAuthGuard
BController
CInjectable
DModule
Attempts:
3 left
💡 Hint
Common Mistakes
Using Controller decorator instead of a guard
Using Injectable which is for services
Using Module which is unrelated here
3fill in blank
hard

Fix the error in the guard class by completing the method signature.

NestJS
canActivate([1]): boolean {
  // logic here
  return true;
}
Drag options to blanks, or click blank then click option'
Aresponse: Response
Bargs: any
Crequest: Request
Dcontext: ExecutionContext
Attempts:
3 left
💡 Hint
Common Mistakes
Using Request or Response directly as parameters
Using a generic 'args' parameter
Omitting the parameter
4fill in blank
hard

Fill both blanks to create a guard that checks if a user is authenticated.

NestJS
import { Injectable, CanActivate, [1] } from '@nestjs/common';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate([2]): boolean {
    const request = context.switchToHttp().getRequest();
    return !!request.user;
  }
}
Drag options to blanks, or click blank then click option'
AExecutionContext
BRequest
Ccontext: ExecutionContext
Dresponse: Response
Attempts:
3 left
💡 Hint
Common Mistakes
Using Request or Response instead of ExecutionContext
Omitting the parameter name or type
Importing wrong types
5fill in blank
hard

Fill all three blanks to apply the AuthGuard to a controller route.

NestJS
import { Controller, Get, [1] } from '@nestjs/common';

@Controller('users')
export class UserController {
  @[2]([3])
  @Get('dashboard')
  getDashboard() {
    return 'Dashboard data';
  }
}
Drag options to blanks, or click blank then click option'
AUseGuards
BAuthGuard
CUseGuards(AuthGuard)
DInjectable
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to import or use AuthGuard as a decorator
Using Injectable instead of UseGuards
Putting UseGuards inside the decorator parentheses incorrectly