Backend Boilerplates typescript Intermediate

NestJS Guards with Roles

NestJS role-based access control using a custom guard and a roles decorator.

typescript
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}
  canActivate(ctx: ExecutionContext): boolean {
    const roles = this.reflector.get<string[]>('roles', ctx.getHandler());
    if (!roles) return true;
    const { user } = ctx.switchToHttp().getRequest();
    return roles.includes(user.role);
  }
}

Prerequisites

  • NestJS >= 10
  • @nestjs/core

Pro Tips

  • → Apply globally in AppModule providers.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
typescript
Level
Intermediate
Read time
4 min
Published
Jul 2024
License
Commercial License

Newsletter

New modules every week, directly to your inbox.