0
0
NestJSframework~3 mins

Why Reflector and custom decorators in NestJS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a few lines of code can save you hours of repetitive checks and bugs!

The Scenario

Imagine you have to check user permissions on every route manually by writing repetitive code inside each controller method.

You also want to add metadata to routes to control behavior, but you have to manage this metadata yourself everywhere.

The Problem

Manually checking permissions and managing metadata leads to duplicated code, mistakes, and makes your app hard to maintain.

It's easy to forget checks or mix up metadata, causing bugs and security holes.

The Solution

Using Reflector and custom decorators lets you attach metadata cleanly to routes or classes and read it easily in one place.

This keeps your code DRY, organized, and secure by centralizing permission checks and metadata handling.

Before vs After
Before
if (user.role !== 'admin') { throw new ForbiddenException(); } // repeated in every method
After
@Roles('admin') // custom decorator
@UseGuards(RolesGuard) // guard uses Reflector to read metadata
What It Enables

You can build flexible, reusable, and clear access control and behavior rules across your app with minimal repeated code.

Real Life Example

In a company app, you tag routes with roles like @Roles('manager') and the guard automatically blocks unauthorized users without extra code in each method.

Key Takeaways

Manual permission checks cause repeated, error-prone code.

Reflector reads metadata set by custom decorators to centralize logic.

This makes your app cleaner, safer, and easier to maintain.