0Pricing
NestJS Enterprise Backend APIs · Lesson

Attaching Metadata with SetMetadata and Reflector

Define route-level metadata and read it back inside guards and interceptors via the Reflector service.

Why Route Metadata?

In an enterprise NestJS API you often need to tag a route with extra information that guards, interceptors, or pipes can read later. Examples include required roles, permission flags, cache TTLs, or a flag that marks a route as public.

NestJS solves this with metadata reflection: you attach key/value data to a handler or controller class, then read it back at request time using the Reflector service. This keeps cross-cutting concerns out of your business logic.

  • SetMetadata — writes the metadata onto the route.
  • Reflector — reads it back inside guards/interceptors.

Attaching Metadata with SetMetadata

SetMetadata(key, value) is a decorator factory from @nestjs/common. You give it a string key and any value, and apply it to a controller method (or whole class).

Here we tag the findAll handler with a list of roles allowed to call it. The metadata is stored against the route handler but does nothing on its own until something reads it.

import { Controller, Get, SetMetadata } from '@nestjs/common';

@Controller('reports')
export class ReportsController {
  @Get()
  @SetMetadata('roles', ['admin', 'manager'])
  findAll() {
    return ['Q1 report', 'Q2 report'];
  }
}

All lessons in this course

  1. Reading Request Context with Param Decorators
  2. Attaching Metadata with SetMetadata and Reflector
  3. Composing Decorators with applyDecorators
  4. Class-Level Decorators for Cross-Cutting Config
← Back to NestJS Enterprise Backend APIs