0
0
NestJSframework~10 mins

Reflector and custom decorators in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Reflector and custom decorators
Define Custom Decorator
Attach Metadata to Target
Use Reflector in Guard/Interceptor
Read Metadata from Target
Make Decisions Based on Metadata
Allow or Deny Access / Modify Behavior
This flow shows how a custom decorator adds metadata to a target, and how Reflector reads that metadata to influence behavior.
Execution Sample
NestJS
import { SetMetadata } from '@nestjs/common';

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

// In a guard
const roles = this.reflector.get<string[]>('roles', context.getHandler());
Defines a custom decorator 'Roles' that attaches roles metadata, then Reflector reads it in a guard to check access.
Execution Table
StepActionTargetMetadata KeyMetadata ValueResult
1Call Roles('admin', 'user') decoratorController method'roles'['admin', 'user']Metadata attached to method
2Request triggers guardRequest context--Guard starts execution
3Reflector reads metadataController method'roles'['admin', 'user']Roles metadata retrieved
4Guard compares user rolesUser roles-['user']User has 'user' role
5Decision based on roles---Access granted because 'user' role matches
6Request proceeds to handler---Handler executes
7End---Execution complete
💡 Execution stops after handler runs or access denied if roles don't match
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 4Final
metadataKeyundefined'roles''roles''roles''roles'
metadataValueundefined['admin', 'user']['admin', 'user']['admin', 'user']['admin', 'user']
userRolesundefinedundefinedundefined['user']['user']
accessGrantedfalsefalsefalsetruetrue
Key Moments - 3 Insights
Why does the Reflector need both the metadata key and the target (like method) to get metadata?
Because metadata is attached to specific targets (methods or classes), Reflector must know where to look. Step 3 shows Reflector reading 'roles' metadata from the controller method.
What happens if the user roles do not match the roles metadata?
In Step 5, the guard would deny access, stopping the request before the handler runs. This is why the decision step is crucial.
Can custom decorators attach any kind of data as metadata?
Yes, custom decorators can attach any data type as metadata using SetMetadata, as shown in Step 1 attaching an array of strings.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the metadata value retrieved by Reflector at Step 3?
Aundefined
B['user']
C['admin', 'user']
D['guest']
💡 Hint
Check the 'Metadata Value' column at Step 3 in the execution table.
At which step does the guard decide to allow access based on user roles?
AStep 5
BStep 2
CStep 4
DStep 6
💡 Hint
Look at the 'Result' column describing the decision in the execution table.
If the user roles were ['guest'] instead of ['user'], what would change in the execution table?
AReflector would fail to read metadata
BStep 5 would deny access instead of granting it
CMetadata value would change at Step 3
DHandler would execute anyway
💡 Hint
Consider the 'Result' column at Step 5 and how user roles affect access.
Concept Snapshot
Custom decorators use SetMetadata to attach data to classes or methods.
Reflector reads this metadata during runtime.
Guards or interceptors use Reflector to get metadata and decide behavior.
This enables flexible, reusable access control or behavior modification.
Always specify metadata key and target when using Reflector.
Full Transcript
This lesson shows how to create a custom decorator in NestJS that attaches metadata to a controller method using SetMetadata. The Reflector class is then used in a guard to read this metadata at runtime. The guard compares the metadata roles with the user's roles to decide if access should be granted. The execution table traces each step: attaching metadata, triggering the guard, reading metadata, checking user roles, making a decision, and finally allowing the request to proceed or denying it. Variables like metadataKey, metadataValue, userRoles, and accessGranted change as the code runs. Key moments clarify why Reflector needs the target to read metadata, what happens if roles don't match, and that custom decorators can attach any data. The quiz tests understanding of metadata retrieval, decision steps, and effects of different user roles. This visual execution helps beginners see how decorators and Reflector work together in NestJS to control access and behavior dynamically.