- Published
- Author
- Sudeep Hipparge
How Decorators Work in NestJS
Decorators in NestJS are a powerful way to attach metadata to routes, classes, or parameters. Today, I implemented a custom
✨ Example:
✅ Custom Decorator:
This attaches metadata like
✅ Guard to Read Metadata
✅ Controller Usage
Under the hood, decorators use
✅ Takeaway: Custom decorators make your code cleaner, declarative, and easier to manage — especially when dealing with role-based access in multi-user systems.
#typescript #NestJs
Decorators in NestJS are a powerful way to attach metadata to routes, classes, or parameters. Today, I implemented a custom
@Roles() decorator to control access to certain routes based on user roles.✨ Example:
✅ Custom Decorator:
@Roles()TypeScript
// roles.decorator.ts
import { SetMetadata } from '@nestjs/common';
export const Roles = (...roles: string[]) => SetMetadata('roles', roles);This attaches metadata like
roles = ['Admin'] to the route handler.✅ Guard to Read Metadata
Code
// roles.guard.ts
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.get<string[]>(
'roles',
context.getHandler()
);
const request = context.switchToHttp().getRequest();
const user = request.user;
return requiredRoles?.includes(user?.role); // Check if user has the role
}
}✅ Controller Usage
Code
@UseGuards(RolesGuard)
@Roles('Admin')
@Patch(':id')
updateOrg() {
// This route is accessible only to users with the 'Admin' role
}Under the hood, decorators use
Reflect.defineMetadata to attach metadata, and NestJS’s Reflector service helps retrieve that metadata in guards or interceptors.✅ Takeaway: Custom decorators make your code cleaner, declarative, and easier to manage — especially when dealing with role-based access in multi-user systems.
#typescript #NestJs