Class-Level Decorators for Cross-Cutting Config
Tag controllers and providers with custom class decorators to drive feature flags and tenant scoping.
Why Class-Level Decorators?
In an enterprise NestJS API, some configuration applies to a whole controller or provider, not a single route. Think feature flags, tenant scoping, audit categories, or rate-limit tiers.
- Repeating this on every method is noisy and error-prone.
- A class-level decorator lets you tag the class once and read that tag later.
The pattern: attach metadata to the class, then read it inside a guard, interceptor, or middleware to drive cross-cutting behavior.
Decorators Are Just Functions
A class decorator is a function that receives the class constructor as its only argument. You can wrap it in a factory so callers pass options.
Here is the raw shape, with no framework involved, so you can see exactly what runs at class-definition time.
// Plain TypeScript: a class decorator factory
function Tag(label: string) {
return function (target: Function) {
console.log(`Decorating ${target.name} with label=${label}`);
};
}
@Tag('billing')
class InvoiceController {}
console.log('Class defined:', InvoiceController.name);All lessons in this course
- Reading Request Context with Param Decorators
- Attaching Metadata with SetMetadata and Reflector
- Composing Decorators with applyDecorators
- Class-Level Decorators for Cross-Cutting Config