0
0
NestJSframework~30 mins

Role-based guards in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Role-based Guards in NestJS
📖 Scenario: You are building a simple NestJS backend for a company. Different users have different roles like admin and user. You want to protect certain routes so only users with the right role can access them.
🎯 Goal: Create a role-based guard in NestJS that checks if a user has the required role before allowing access to a route.
📋 What You'll Learn
Create a roles array to hold user roles
Create a constant for the required role
Implement a guard class that checks user roles
Apply the guard to a controller route
💡 Why This Matters
🌍 Real World
Role-based guards are used in real applications to restrict access to certain parts of a backend API based on user permissions.
💼 Career
Understanding role-based guards is essential for backend developers working with NestJS to build secure and maintainable applications.
Progress0 / 4 steps
1
Create a roles array
Create a constant array called roles with the exact values 'admin' and 'user'.
NestJS
Need a hint?

Use const roles = ['admin', 'user']; to create the array.

2
Create a required role constant
Create a constant called requiredRole and set it to the string 'admin'.
NestJS
Need a hint?

Use const requiredRole = 'admin'; to set the required role.

3
Implement the role guard class
Create a class called RolesGuard that implements CanActivate. Inside, write a canActivate method that takes context and returns true only if requiredRole is included in roles.
NestJS
Need a hint?

Use roles.includes(requiredRole) inside canActivate to check the role.

4
Apply the guard to a controller route
In a controller class called AppController, create a method getAdminData decorated with @Get('admin') and @UseGuards(RolesGuard). The method should return the string 'Admin content'.
NestJS
Need a hint?

Use @UseGuards(RolesGuard) above the method to protect the route.