skip to content

In NestJS 12, how does a guard read metadata from a Reflector.createDecorator decorator, and when do getAllAndOverride and getAllAndMerge differ?

level: middleimportance: should knowfreq 50%

answer

  1. decorators write, Reflector reads
  2. handler and class are two targets
  3. first defined value versus combined
  4. a generated key on KEY

basics

~10 s

Inject Reflector and pass it the decorator plus targets from the ExecutionContext. getAllAndOverride(Dec, [context.getHandler(), context.getClass()]) returns the first defined value, so the method overrides the controller; getAllAndMerge concatenates arrays or shallow-merges objects from both.

solid answer

~40 s

`Reflector.createDecorator<T>()` from `@nestjs/core` returns a typed decorator that stores its argument as metadata on whatever it decorates, under a generated key exposed as `.KEY` unless you pass a `key` option. A guard injects `Reflector` and reads it back by passing the **decorator reference** and a target: `reflector.get(Dec, context.getHandler())` reads the method only. When the decorator may sit on the controller and the method, pass both targets. `getAllAndOverride(Dec, [context.getHandler(), context.getClass()])` returns the first value that is not `undefined`, so a method-level value replaces the controller's, and it returns `undefined` when neither has one. `getAllAndMerge` collects both: arrays are concatenated in target order, objects are shallow-merged, and with no metadata at all it returns an empty array, which is truthy. `@SetMetadata('key', value)` is the low-level alternative, read back with the same string key.

code

typescript · 47 lines
typescript
import {
  CanActivate,
  Controller,
  ExecutionContext,
  Get,
  Injectable,
  UseGuards,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { FeatureFlags } from './feature-flags.js';

export const RequireFeatures = Reflector.createDecorator<string[]>();

@Injectable()
export class FeatureGuard implements CanActivate {
  constructor(
    private readonly reflector: Reflector,
    private readonly flags: FeatureFlags,
  ) {}

  canActivate(context: ExecutionContext): boolean {
    const required = this.reflector.getAllAndOverride(RequireFeatures, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (!required) {
      return true;
    }
    return required.every((name) => this.flags.isOn(name));
  }
}

@Controller('reports')
@UseGuards(FeatureGuard)
@RequireFeatures(['reports'])
export class ReportsController {
  @Get()
  list() {
    return [];
  }

  @Get('export')
  @RequireFeatures(['reports-export'])
  exportCsv() {
    return [];
  }
}

go deeper

for a junior

Recall that decorators write metadata, Reflector reads it, and the guard gets the targets from context.getHandler() and context.getClass().

for a middle

Explain getAllAndOverride versus getAllAndMerge on the same handler and controller, including what each returns when nothing is set and why createDecorator values must be read by the decorator reference.

for a senior

Diagnose a class-level decorator that does nothing (read from the handler only), a merge guard that never takes its default branch, and an object merge where the controller's key silently wins.

for a principal

Set a house rule for metadata decorators: createDecorator with typed values, a documented override-or-merge semantic per decorator, and tests that cover the class-level and method-level placements.

## Why guards need metadata A guard that applies the same rule to every route is rarely enough. Usually the rule varies per route: this endpoint needs a feature to be switched on, that one is open. NestJS solves this with **metadata**: a decorator attaches a value to a controller class or a handler method, and a guard or interceptor reads it at request time through the `ExecutionContext`, whose `getHandler()` and `getClass()` identify the method and controller that are about to run. The write side and the read side both belong to `Reflector`, imported from `@nestjs/core`. ## Writing metadata There are two ways to attach a value. - **`Reflector.createDecorator<T>()`** returns a strongly typed decorator, for example `export const RequireFeatures = Reflector.createDecorator<string[]>();`. Applying `@RequireFeatures(['reports'])` stores `['reports']` on the target. - The metadata key is **generated** (a random 21-character id) unless you pass `{ key: '...' }`; the decorator exposes it as `RequireFeatures.KEY`. - An optional `transform` function rewrites the argument before it is stored. - Called with no argument, the decorator stores an empty object, so a bare flag decorator still leaves a defined value. - **`@SetMetadata(key, value)`** from `@nestjs/common` is the low-level form. The docs advise wrapping it in your own decorator, `export const Features = (...names: string[]) => SetMetadata('features', names);`, which gives you control over the key and lets the decorator take several arguments. ## Reading metadata A guard injects `Reflector` in its constructor and calls one of four methods. Each takes a decorator reference (or a metadata key) and one or more targets. | Method | Reads | Result when nothing is set | |---|---|---| | `get(Dec, target)` | one target | `undefined` | | `getAll(Dec, targets)` | each target, as an array of results | an array of `undefined` values | | `getAllAndOverride(Dec, targets)` | targets in order, first value that is not `undefined` | `undefined` | | `getAllAndMerge(Dec, targets)` | every target, combined | `[]` | For a controller decorated `@RequireFeatures(['reports'])` whose `exportCsv()` method adds `@RequireFeatures(['reports-export'])`, reading with `[context.getHandler(), context.getClass()]` gives: | Call | `GET /reports` (no method metadata) | `GET /reports/export` | |---|---|---| | `get(RequireFeatures, context.getHandler())` | `undefined` | `['reports-export']` | | `getAllAndOverride(...)` | `['reports']` | `['reports-export']` | | `getAllAndMerge(...)` | `['reports']` | `['reports-export', 'reports']` | ## How getAllAndMerge combines values The merge rules come straight from the `Reflector` source: - `undefined` results are dropped first. - Arrays are **concatenated** in the order of the targets you pass. - Objects are **shallow-merged** with object spread, so a key from a later target overwrites the same key from an earlier one. With `[handler, class]`, the class wins a key conflict, which surprises people who expect the method to win. - A single result that is an object (an array counts) is returned as it is; a single scalar, such as a string, comes back wrapped in an array. - With nothing found, the result is an empty array. ## Bugs this API produces in practice 1. **Reading one target.** `reflector.get(Dec, context.getHandler())` ignores a decorator placed on the controller, so a class-level rule silently does nothing. 2. **Reading by the wrong key.** A `createDecorator()` value lives under its generated key, so `reflector.get('requireFeatures', ...)` returns `undefined`. Pass the decorator itself, or give it an explicit `key`. 3. **Testing a merge result for absence.** `getAllAndMerge` returns `[]` when nothing is set, and an empty array is truthy, so `if (!required) return true;` never takes that branch. Check `.length`, or use `getAllAndOverride`, which returns `undefined`. 4. **Choosing override when you meant merge.** If the controller says `['reports']` and a method says `['reports-export']`, override checks only the method's requirement. Decide which semantics the decorator promises and write it down next to it. ## createDecorator or SetMetadata Both write the same kind of metadata; the difference is ergonomics and safety. - `Reflector.createDecorator<T>()` gives a **typed** argument (`@RequireFeatures(['reports'])` fails to compile with a number) and a key nobody can mistype, because readers pass the decorator itself. - `@SetMetadata('features', names)` wrapped in a factory lets the decorator take **several arguments** (`@Features('reports', 'beta')`) and uses a key you choose, which matters when another library must read the same metadata by name. - Whichever you pick, export the decorator from one module and read it only through that export, so the key has one owner. ## Where this is used beyond guards Interceptors receive the same `ExecutionContext`, so they read metadata the same way. Nest's own `ClassSerializerInterceptor` reads its `@SerializeOptions()` metadata with `getAllAndOverride` over the handler and the class, which is why a handler's options replace the controller's instead of merging with them.

  • Why does reflector.get('requireFeatures', context.getHandler()) return undefined in NestJS when the handler carries a Reflector.createDecorator decorator?
    `createDecorator()` stores the value under a generated 21-character key unless you pass a `key` option, so a hand-typed string never matches. Pass the decorator reference, `reflector.get(RequireFeatures, context.getHandler())`; `Reflector` looks up its `.KEY` for you. A string key works only for metadata written with `@SetMetadata()` or a decorator created with an explicit `key`.
  • In NestJS, what does getAllAndMerge return when neither the handler nor the controller has the metadata, and why does it matter?
    It returns an empty array, while `getAllAndOverride` returns `undefined`. An empty array is truthy, so a guard written `if (!required) return true;` skips its no-metadata branch and goes on to evaluate an empty requirement list, where `[].every(...)` is `true` and `[].some(...)` is `false`. Test `required.length` explicitly when you merge.

  • reflector.get(Dec, context.getHandler()) also returns metadata placed on the controller class.
  • getAllAndOverride merges the handler's and the controller's arrays into one list.
  • A Reflector.createDecorator value can be read back with the variable name as a string key.
  • getAllAndMerge returns undefined when no target carries the metadata.
  • When getAllAndMerge combines two objects, the handler's keys always win over the controller's.