0
0
NestJSframework~30 mins

Guard interface (canActivate) in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Create a Simple Guard Using canActivate in NestJS
📖 Scenario: You are building a NestJS backend for a small app. You want to protect a route so only users with a specific role can access it.
🎯 Goal: Build a guard using the canActivate method that allows access only if the user role is admin.
📋 What You'll Learn
Create a guard class named RolesGuard that implements CanActivate
Add a canActivate method that checks if the user role is admin
Use the ExecutionContext to get the request object
Return true if the role is admin, otherwise false
Apply the guard to a sample controller route
💡 Why This Matters
🌍 Real World
Guards are used in real NestJS apps to protect routes and APIs based on user roles or permissions.
💼 Career
Understanding guards and canActivate is essential for backend developers working with NestJS to build secure applications.
Progress0 / 4 steps
1
Create the RolesGuard class implementing CanActivate
Create a class called RolesGuard that implements the CanActivate interface from @nestjs/common.
NestJS
Need a hint?

Remember to import CanActivate and ExecutionContext from @nestjs/common.

2
Extract the user role from the request object
Inside the canActivate method, use context.switchToHttp().getRequest() to get the request object. Then create a variable called userRole that gets the role property from request.user.
NestJS
Need a hint?

Use context.switchToHttp().getRequest() to get the request, then access user.role.

3
Check if the user role is 'admin' and return true or false
Update the canActivate method to return true if userRole equals 'admin'. Otherwise, return false.
NestJS
Need a hint?

Use a simple comparison to check if userRole is 'admin'.

4
Apply the RolesGuard to a controller route
Create a controller class called AppController with a method getAdminData decorated with @Get('admin'). Apply the RolesGuard to this method using @UseGuards(RolesGuard). The method should return the string 'Admin data'.
NestJS
Need a hint?

Import Controller, Get, and UseGuards from @nestjs/common. Decorate the method and class properly.