How do you implement role-based access control (RBAC) in NestJS?
Answer
RBAC in NestJS uses the combination of custom decorators and guards. Step 1: Create a decorator to set required roles metadata: export const Roles = (...roles: Role[]) => SetMetadata('roles', roles);. Step 2: Create a RolesGuard that reads this metadata: const requiredRoles = this.reflector.getAllAndOverride<Role[]>('roles', [context.getHandler(), context.getClass()]); then checks req.user.roles. Step 3: Apply globally or per-route: @Roles(Role.Admin) @UseGuards(JwtAuthGuard, RolesGuard) @Delete('/:id'). The JWT guard runs first (sets req.user), then the roles guard checks permissions. This pattern is clean, declarative, and easily testable.
Previous
What is the ExecutionContext in NestJS?
Next
What is the Reflector in NestJS and how is it used?
More NestJS Questions
View all →- Intermediate How does NestJS dependency injection scoping work?
- Intermediate What are NestJS microservices and what transports are supported?
- Intermediate What is the ExecutionContext in NestJS?
- Intermediate What is the Reflector in NestJS and how is it used?
- Intermediate How do you implement caching in NestJS?