🦅 NestJS Intermediate

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.