What is the Reflector in NestJS and how is it used?
Answer
The Reflector is a utility class provided by NestJS (@nestjs/core) that allows reading metadata attached to routes and controllers via decorators. Inject it: constructor(private reflector: Reflector) {}. Read metadata: this.reflector.get<string[]>('roles', context.getHandler()). The key insight: getAllAndOverride checks both the handler method and the controller class, with the method-level metadata taking precedence — useful for applying defaults at the controller level and overriding per-method. getAllAndMerge merges arrays from both levels. The Reflector is the bridge between SetMetadata decorators (which store metadata) and Guards/Interceptors (which read it), enabling declarative, metadata-driven authorization patterns.
Previous
How do you implement role-based access control (RBAC) in NestJS?
Next
How do you implement caching in NestJS?
More NestJS Questions
View all →- Intermediate How does NestJS dependency injection scoping work?
- Intermediate What are NestJS microservices and what transports are supported?
- Intermediate What is the ExecutionContext in NestJS?
- Intermediate How do you implement role-based access control (RBAC) in NestJS?
- Intermediate How do you implement caching in NestJS?