• Residence: Bosnia & Herzegovina
  • City: Bijeljina
  • Age: 26
DOWNLOAD CV
Back to Blog

Module-Based RBAC in NestJS: Permissions That Scale Past Admin and User

· Đorđije Lazarević · 3 min read

Most NestJS apps start with a Role enum and a @Roles('admin') decorator. It works until the first B2B client asks for "a sales rep who can create quotes but not approve them" or "an accountant who sees invoices but not salaries". At that point roles hard-coded in the code base become the bottleneck.

This is the pattern I use instead: permissions are checked in code, roles are data. Admins combine permissions into roles at runtime, and the code never asks "is this user an admin?".

The model: module and action

Every permission is a pair of an application module and an action, written as module:action. TypeScript template literal types keep the list closed, so a typo fails at compile time.

export const MODULES = ['invoices', 'quotes', 'products', 'users'] as const;
export const ACTIONS = ['read', 'create', 'update', 'delete', 'approve'] as const;

export type ModuleKey = (typeof MODULES)[number];
export type Action = (typeof ACTIONS)[number];
export type Permission = `${ModuleKey}:${Action}`;

A role is a name and a list of permissions. A user can have several roles. Storing the permissions on the role keeps reads simple:

@Entity()
export class Role {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ unique: true })
  name: string;

  // e.g. ['quotes:read', 'quotes:create']
  @Column('simple-array')
  permissions: Permission[];
}

Note that approve is its own action, separate from update. Approval workflows (B2B account onboarding, discounts above a limit) are the main reason clients ask for custom roles, so they deserve a permission of their own.

Decorator and guard

export const PERMISSIONS_KEY = 'permissions';
export const RequirePermissions = (...permissions: Permission[]) =>
  SetMetadata(PERMISSIONS_KEY, permissions);

@Injectable()
export class PermissionsGuard implements CanActivate {
  constructor(
    private readonly reflector: Reflector,
    private readonly permissions: PermissionsService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const required = this.reflector.getAllAndOverride<Permission[]>(PERMISSIONS_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (!required?.length) return true;

    const { user } = context.switchToHttp().getRequest();
    if (!user) return false;

    const granted = await this.permissions.forUser(user.id);
    return required.every((permission) => granted.has(permission));
  }
}

In a controller, authentication runs first and the permission check second:

@Controller('quotes')
@UseGuards(JwtAuthGuard, PermissionsGuard)
export class QuotesController {
  @Get()
  @RequirePermissions('quotes:read')
  list() { /* ... */ }

  @Post(':id/approve')
  @RequirePermissions('quotes:approve')
  approve(@Param('id') id: string) { /* ... */ }
}

Caching without stale permissions

forUser loads the user's roles and merges their permissions into a Set. Doing that on every request is wasteful, so I cache the set per user. The catch is invalidation: when an admin edits a role, every user with that role must lose or gain access immediately.

The simplest reliable approach is a version number. Each role has a version column that increases on every change; the cache key includes the sum or hash of the user's role versions. Editing a role changes the key, and old entries expire on their own. No one has to remember to clear the cache in every code path.

Ownership is not a role

RBAC answers "may this user approve quotes?". It does not answer "may this user see this particular quote?". Row-level rules (a sales rep sees only their own customers, a branch manager only their branch) belong in the service or the query, where the data is loaded:

findForUser(user: AuthUser, id: string) {
  const where: FindOptionsWhere<Quote> = { id };
  if (!user.permissions.has('quotes:read-all')) where.ownerId = user.id;
  return this.quotes.findOne({ where });
}

Mixing the two into the guard is the most common way these systems become unreadable.

The frontend gets the list, not the decision

An endpoint such as GET /me/permissions returns the user's set so the React or React Native app can hide buttons the user cannot use. That is a user experience feature only. Every rule is still enforced by the API.

Testing the guard

it('denies access when a permission is missing', async () => {
  const reflector = {
    getAllAndOverride: jest.fn().mockReturnValue(['quotes:approve']),
  } as unknown as Reflector;
  const permissions = {
    forUser: jest.fn().mockResolvedValue(new Set(['quotes:read'])),
  } as unknown as PermissionsService;
  const context = {
    getHandler: () => null,
    getClass: () => null,
    switchToHttp: () => ({ getRequest: () => ({ user: { id: 1 } }) }),
  } as unknown as ExecutionContext;

  const guard = new PermissionsGuard(reflector, permissions);
  await expect(guard.canActivate(context)).resolves.toBe(false);
});

I use this module-based design on B2B platforms with staff permissions, sales-rep-assisted ordering and approval workflows. Adding a new module means adding one entry to MODULES; adding a new job title for a client means creating a role in the admin panel, with no deployment.

Planning a React Native app?

I take on freelance projects for clients across DACH and the EU: React and Next.js web apps, React Native mobile apps and NestJS backends, from architecture to production. Remote, CET time zone.