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 CanActivateAdd a
canActivate method that checks if the user role is adminUse the
ExecutionContext to get the request objectReturn
true if the role is admin, otherwise falseApply 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