Metadata Decorators

SetMetadata and Reflector.createDecorator

Metadata decorators do not run code; they attach data that guards and interceptors read. You saw @Roles() in the Guards module. Another common one is @Public() to skip a global auth guard (used in the advanced level).

import { SetMetadata } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

export const IS_PUBLIC_KEY = 'isPublic';
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);

// typed alternative (NestJS 10.2+)
export const RateLimit = Reflector.createDecorator<{ limit: number; ttlMs: number }>();

// controller
// @Public() @Get('health') health() { return { status: 'ok' }; }
// @RateLimit({ limit: 5, ttlMs: 60_000 }) @Post('otp') sendOtp() {}

// guard
// const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [ctx.getHandler(), ctx.getClass()]);
// const rule = this.reflector.get(RateLimit, ctx.getHandler());