Bird
Raised Fist0
NestJSframework~5 mins

Role-based guards in NestJS

Choose your learning style10 modes available
Introduction

Role-based guards help control who can access certain parts of your app based on their role. They keep your app safe by allowing only the right users to do specific actions.

You want only admins to access the admin dashboard.
You want to restrict editing rights to managers only.
You want to show certain pages only to logged-in users with specific roles.
You want to prevent guests from accessing user settings.
You want to protect API routes based on user roles.
Syntax
NestJS
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const requiredRoles = this.reflector.get<string[]>('roles', context.getHandler());
    if (!requiredRoles) {
      return true;
    }
    const { user } = context.switchToHttp().getRequest();
    return requiredRoles.some(role => user.roles?.includes(role));
  }
}

The guard uses Reflector to read roles metadata set on route handlers.

The canActivate method returns true if the user has any required role.

Examples
This example shows how to set roles metadata on a route using a custom @Roles decorator.
NestJS
@Roles('admin')
@Get('admin')
getAdminData() {
  return 'Admin data';
}
This is the custom @Roles decorator that attaches roles metadata to routes.
NestJS
import { SetMetadata } from '@nestjs/common';

export const Roles = (...roles: string[]) => SetMetadata('roles', roles);
Here, the RolesGuard protects the getProfile route, allowing only users with 'user' or 'admin' roles.
NestJS
@UseGuards(RolesGuard)
@Controller('users')
export class UsersController {
  @Roles('user', 'admin')
  @Get('profile')
  getProfile() {
    return 'User profile';
  }
}
Sample Program

This example shows a simple NestJS controller with two routes protected by the RolesGuard. Only users with the 'admin' role can access the admin dashboard, and only users with the 'user' role can access the user dashboard.

NestJS
import { Controller, Get, UseGuards } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { CanActivate, ExecutionContext, Injectable, SetMetadata } from '@nestjs/common';

export const Roles = (...roles: string[]) => SetMetadata('roles', roles);

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const requiredRoles = this.reflector.get<string[]>('roles', context.getHandler());
    if (!requiredRoles) {
      return true;
    }
    const { user } = context.switchToHttp().getRequest();
    return requiredRoles.some(role => user.roles?.includes(role));
  }
}

@UseGuards(RolesGuard)
@Controller('dashboard')
export class DashboardController {
  @Roles('admin')
  @Get('admin')
  getAdminDashboard() {
    return 'Welcome to Admin Dashboard';
  }

  @Roles('user')
  @Get('user')
  getUserDashboard() {
    return 'Welcome to User Dashboard';
  }
}
OutputSuccess
Important Notes

Make sure your authentication system adds a user object with roles to the request.

Use the @Roles decorator to specify which roles can access a route.

Guards run before route handlers to block unauthorized access early.

Summary

Role-based guards control access by checking user roles before running route code.

Use a custom @Roles decorator to mark routes with allowed roles.

Implement canActivate in a guard to allow or deny access based on roles.

Practice

(1/5)
1. What is the main purpose of a role-based guard in NestJS?
easy
A. To manage application configuration
B. To handle database connections
C. To format HTTP responses
D. To restrict access to routes based on user roles

Solution

  1. Step 1: Understand role-based guard function

    Role-based guards check user roles before allowing access to routes.
  2. Step 2: Identify the correct purpose

    Restricting access based on roles matches the guard's role in security.
  3. Final Answer:

    To restrict access to routes based on user roles -> Option D
  4. Quick Check:

    Role-based guard = restrict access by roles [OK]
Hint: Guards control access; roles limit who can enter [OK]
Common Mistakes:
  • Confusing guards with database or config management
  • Thinking guards format responses
  • Assuming guards handle unrelated tasks
2. Which of the following is the correct way to apply a role-based guard to a route in NestJS?
easy
A. @UseGuards(RolesGuard)\n@Get('profile')
B. @Controller('profile')\n@RolesGuard()
C. @Roles('admin')\n@UseGuards(AuthGuard)
D. @UseGuards(AuthGuard)\n@Get('profile')

Solution

  1. Step 1: Identify correct guard usage syntax

    Use @UseGuards with the guard class to apply it to routes.
  2. Step 2: Match with role-based guard usage

    @UseGuards(RolesGuard) is correct; @Roles decorator marks roles separately.
  3. Final Answer:

    @UseGuards(RolesGuard)\n@Get('profile') -> Option A
  4. Quick Check:

    @UseGuards(RolesGuard) applies guard [OK]
Hint: Use @UseGuards with guard class to protect routes [OK]
Common Mistakes:
  • Using @RolesGuard() instead of @UseGuards
  • Mixing @Roles and @UseGuards incorrectly
  • Applying guards without @UseGuards decorator
3. Given this guard code snippet, what will be the result if the user role is 'user' and the route requires 'admin' role?
canActivate(context: ExecutionContext) {
  const roles = this.reflector.get('roles', context.getHandler());
  const request = context.switchToHttp().getRequest();
  const user = request.user;
  return roles.includes(user.role);
}
medium
A. Access granted
B. Access denied
C. Runtime error due to missing roles
D. Always returns true

Solution

  1. Step 1: Understand role check logic

    The guard checks if the user's role is included in the allowed roles array.
  2. Step 2: Apply given roles and user role

    User role is 'user', route requires 'admin', so roles.includes('user') is false.
  3. Final Answer:

    Access denied -> Option B
  4. Quick Check:

    User role not in allowed roles = deny access [OK]
Hint: Check if user role is in allowed roles array [OK]
Common Mistakes:
  • Assuming access is granted if roles differ
  • Thinking roles includes user role always
  • Ignoring roles array presence
4. Identify the error in this role-based guard implementation:
canActivate(context: ExecutionContext) {
  const roles = this.reflector.get('roles', context.getHandler());
  const request = context.switchToHttp().getRequest();
  const user = request.user;
  if (!roles) {
    return false;
  }
  return roles.includes(user.role);
}
medium
A. Returns false if no roles metadata, blocking all access
B. Missing async keyword causes runtime error
C. Incorrect use of context.getHandler()
D. Should check user permissions instead of roles

Solution

  1. Step 1: Analyze roles metadata check

    If roles metadata is missing, the guard returns false blocking access.
  2. Step 2: Understand typical behavior for missing roles

    Usually, missing roles means no restriction, so returning false is too strict.
  3. Final Answer:

    Returns false if no roles metadata, blocking all access -> Option A
  4. Quick Check:

    No roles metadata should allow access, not block [OK]
Hint: Missing roles metadata should not block access by default [OK]
Common Mistakes:
  • Assuming missing roles means deny access
  • Forgetting to handle undefined roles gracefully
  • Confusing async necessity in this context
5. You want to create a role-based guard that allows access if the user has any one of multiple roles specified on a route. Which approach correctly implements this behavior?
hard
A. Use multiple guards each checking one role and combine them with @UseGuards
B. Check only the first role in roles array against user.role in canActivate
C. Use @Roles('admin', 'editor') decorator and check if user.role is included in roles array inside canActivate
D. Ignore roles and allow access to all authenticated users

Solution

  1. Step 1: Understand multiple roles in @Roles decorator

    @Roles can accept multiple roles as arguments to specify allowed roles.
  2. Step 2: Implement canActivate to check inclusion

    Checking if user.role is in roles array allows access if user has any allowed role.
  3. Final Answer:

    Use @Roles('admin', 'editor') decorator and check if user.role is included in roles array inside canActivate -> Option C
  4. Quick Check:

    Check user role in roles array for multiple allowed roles [OK]
Hint: Check if user role is in roles array for multiple roles [OK]
Common Mistakes:
  • Checking only first role ignores others
  • Using multiple guards unnecessarily
  • Allowing all authenticated users ignores roles
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard