0
0
NestJSframework~30 mins

Reflector and custom decorators in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Reflector and Custom Decorators in NestJS
📖 Scenario: You are building a NestJS application that needs to handle user roles for access control. You want to create a custom decorator to mark which roles can access certain routes, and then use the Reflector service to read these roles inside a guard.
🎯 Goal: Build a custom @Roles() decorator that stores roles metadata on route handlers, and use the Reflector service inside a guard to read this metadata and decide access.
📋 What You'll Learn
Create a custom decorator called Roles that accepts an array of strings representing roles
Use SetMetadata to attach the roles metadata with the key 'roles'
Create a guard class called RolesGuard that injects Reflector
Inside the guard, use Reflector.getAllAndOverride to get the roles metadata for the current route handler
Return true from the guard if no roles are set, or if the user has at least one required role
💡 Why This Matters
🌍 Real World
Role-based access control is common in web applications to restrict certain routes to users with specific permissions or roles.
💼 Career
Understanding how to create custom decorators and use Reflector in NestJS is essential for building secure, maintainable backend applications.
Progress0 / 4 steps
1
Create the custom Roles decorator
Create a custom decorator called Roles that uses SetMetadata to attach an array of roles with the key 'roles'. The decorator should accept a parameter called roles which is an array of strings.
NestJS
Need a hint?

Use SetMetadata from @nestjs/common to create the decorator.

2
Create the RolesGuard class and inject Reflector
Create a class called RolesGuard that implements CanActivate. Inject Reflector via the constructor and store it in a private readonly property called reflector.
NestJS
Need a hint?

Use @Injectable() and implement CanActivate. Inject Reflector in the constructor.

3
Use Reflector.getAllAndOverride to get roles metadata inside canActivate
Inside the canActivate method of RolesGuard, use this.reflector.getAllAndOverride with the key 'roles' and pass context.getHandler() and context.getClass() as arguments. Store the result in a variable called requiredRoles.
NestJS
Need a hint?

Use getAllAndOverride with the key 'roles' and pass an array with context.getHandler() and context.getClass().

4
Complete canActivate to check user roles and return access decision
Complete the canActivate method to return true if requiredRoles is undefined. Otherwise, get the user roles from context.switchToHttp().getRequest().user.roles and return true if the user has at least one role in requiredRoles. Return false otherwise.
NestJS
Need a hint?

Check if requiredRoles is undefined, then allow access. Otherwise, get user.roles from the request and check if any role matches.