NestJS Decorator Patterns

VerifiedSafe

Guide to NestJS built-in and custom decorators: routes, parameters, metadata, and composition. Covers createParamDecorator and Reflector.

Sby Skills Guide Bot
DevelopmentIntermediate
11/1/2026
Claude CodeCursorWindsurfCopilotCodex
#nestjs#decorators#typescript#backend#metadata

Recommended for

Automated summary

Guides NestJS developers through built-in and custom decorator usage, decorator composition, and metadata reflection for controllers, guards, and interceptors.

Strengths

  • Covers class, route, and parameter decorators with concise examples.
  • Explains decorator composition and building custom parameter decorators with createParamDecorator and SetMetadata.
  • Highlights the required tsconfig settings and the lifecycle caveat around injecting @Res().
  • Clearly scopes itself against related NestJS skills.

Limitations

  • The content appears cut off mid-sentence in the @Res() section.
  • Complete examples for custom decorators and Reflector usage are not provided.
  • NestJS-specific only, with module/DI, GraphQL, and ORM decorators explicitly excluded.
When to use it

Use when writing or reviewing NestJS controllers, guards, interceptors, or custom decorators that depend on route parameters and metadata.

When not to use it

Do not use for general NestJS module/DI design, GraphQL decorators, ORM entity decorators, or non-NestJS frameworks.

Security analysis

Safe
Quality score90/100

Pure reference documentation for NestJS decorators. It contains only TypeScript snippets illustrating framework APIs (controllers, param decorators, guards, metadata reflection) and never instructs the agent to execute shell commands, touch the network, modify files, or handle secrets. No prompt-injection or instruction-override attempts were present in the content.

No concerns found

How this analysis is made

Examples

Custom current-user decorator
Create a @CurrentUser() param decorator in NestJS that extracts the authenticated user from the request, and show how to use it in a controller method.
Role metadata with Reflector
Show me how to use SetMetadata and Reflector in a NestJS guard to implement role-based access control on controller routes.
Compose guards and interceptors
How do I compose @UseGuards and @UseInterceptors on a NestJS controller while keeping the decorator order and behavior clear?

name: decorator-patterns description: | NestJS decorator usage: built-in route/param/class decorators, custom decorators via createParamDecorator and SetMetadata, metadata reflection via Reflector. Apply when designing controllers, guards, interceptors, or custom decorators.

Use this skill to:

  • Pick the right built-in decorator for routes, params, and DI.
  • Compose decorators (@UseGuards(A, B) @UseInterceptors(C)).
  • Build custom param decorators (e.g., @CurrentUser()).
  • Use metadata for role-based logic (Reflector + SetMetadata).
  • Avoid common decorator mistakes.

Do NOT use this skill for:

  • General module/DI patterns (see nest-conventions).
  • GraphQL-specific decorators (see nest-advanced).
  • ORM entity decorators (see nest-data-layer). user-invocable: false paths: ["src/**/*.ts"]

NestJS Decorator Patterns

NestJS is decorator-driven. Knowing which decorator does what — and how they compose — prevents most "weird DI / weird routing" bugs.

Required tsconfig

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

emitDecoratorMetadata is what makes runtime introspection (and class-validator/class-transformer) work. Never disable.

reflect-metadata polyfill must be imported once at the top of main.ts:

import 'reflect-metadata';

(NestJS does this implicitly via @nestjs/core, but if you write a script that uses decorators outside the Nest app, import it manually.)

Class-level decorators

@Controller(prefix)

@Controller('users')                            // routes prefixed /users
@Controller({ path: 'users', version: '1' })    // versioned: /v1/users (with VersioningType.URI)
export class UsersController {}

@Injectable(options?)

@Injectable()                                   // singleton (default)
@Injectable({ scope: Scope.REQUEST })           // per-request
export class MyService {}

@Module(...)

@Module({ imports, controllers, providers, exports })
export class UsersModule {}

@Global()

@Global()
@Module({ providers: [...], exports: [...] })
export class LoggerModule {}

Use sparingly — see nest-conventions.

Method-level: HTTP routing

@Get()                          // GET /users
@Get(':id')                     // GET /users/:id
@Post()
@Put(':id')
@Patch(':id')
@Delete(':id')
@All('debug')                   // any method
@Head()
@Options()

Route options

@HttpCode(204)                  // override default status (200/201)
@Header('Cache-Control', 'no-store')
@Redirect('https://example.com', 301)
@Render('user-profile')         // for view engines (rare in API-only)

Versioning

@Controller({ path: 'users', version: ['1', '2'] })
@Version('2')                   // override at method level
@Get()
findV2() {}

Param decorators

@Get(':id')
async findOne(
  @Param('id') id: string,                          // route param
  @Query('include') include: string,                // ?include=...
  @Headers('authorization') authHeader: string,     // single header
  @Headers() allHeaders: Record<string, string>,    // all headers
  @Body() dto: UpdateUserDto,                       // request body (validated by ValidationPipe)
  @Body('email') email: string,                     // single field (no DTO validation — avoid)
  @Req() req: Request,                              // raw request (escape hatch)
  @Res() res: Response,                             // raw response (rare; breaks NestJS lifecycle)
  @Ip() ip: string,
  @HostParam() hosts: Record<string, string>,
  @Session() session: Record<string, unknown>,      // requires session middleware
) {}

@Res() warning

When you inject @Res() and call res.send() directly, NestJS skips its response-handling pipeline (interceptors, exception filters that produce a response). Either:

  • Don't inject @Res() — return data and let Nest handle the response.
  • Or inject @Res({ passthrough: true }) and still return data.
@Get()
async getStream(@Res({ passthrough: true }) res: Response): Promise<StreamableFile> {
  res.set({ 'Content-Type': 'application/octet-stream' });
  return new StreamableFile(buffer);
}

Pipe binding

@Get(':id')
findOne(
  @Param('id', ParseIntPipe) id: number,                    // built-in pipe
  @Query('limit', new DefaultValuePipe(20), ParseIntPipe) limit: number,
  @Body(new ValidationPipe({ whitelist: true })) dto: CreateUserDto,
) {}

Pipes run in order, left-to-right. Combine for type-safe + validated input.

Guard / Interceptor / Filter binding

@UseGuards(JwtAuthGuard, RolesGuard)
@UseInterceptors(LoggingInterceptor, CacheInterceptor)
@UseFilters(AllExceptionsFilter)
@UsePipes(new ValidationPipe({ transform: true }))
@Controller('users')
export class UsersController {}

Apply at route level OR globally:

// global guard via DI (preferred — can inject deps)
@Module({
  providers: [
    { provide: APP_GUARD, useClass: JwtAuthGuard },
    { provide: APP_INTERCEPTOR, useClass: LoggingInterceptor },
    { provide: APP_FILTER, useClass: AllExceptionsFilter },
    { provide: APP_PIPE, useClass: ValidationPipe },
  ],
})

// or in main.ts (cannot inject DI)
app.useGlobalGuards(new JwtAuthGuard());

APP_GUARD etc. are imported from @nestjs/core constants.

Metadata via SetMetadata + Reflector

For role-based or feature-flag logic, attach metadata to a route, then read in a guard.

Define a metadata decorator

// src/auth/roles.decorator.ts
import { SetMetadata } from '@nestjs/common';

export const ROLES_KEY = 'roles';
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);

Apply on route

@Controller('admin')
@UseGuards(JwtAuthGuard, RolesGuard)
export class AdminController {
  @Get('users')
  @Roles('admin', 'super-admin')
  listUsers() { ... }
}

Read in guard

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const required = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (!required) return true;
    const { user } = context.switchToHttp().getRequest();
    return required.some(r => user.roles?.includes(r));
  }
}

getAllAndOverride walks handler → class metadata; method-level wins. getAllAndMerge combines both.

Custom param decorator

// src/auth/current-user.decorator.ts
import { createParamDecorator, ExecutionContext } from '@nestjs/common';

export const CurrentUser = createParamDecorator(
  (data: keyof User | undefined, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    const user = request.user as User;
    return data ? user?.[data] : user;
  },
);

Usage:

@Get('me')
me(@CurrentUser() user: User) {}

@Get('email')
myEmail(@CurrentUser('email') email: string) {}

Works in HTTP, GraphQL, WebSocket contexts via switchToHttp / switchToWs / GraphQL execution context wrapper.

Composing decorators

For a frequently-used combo, build a meta-decorator with applyDecorators:

// src/auth/auth.decorator.ts
import { applyDecorators, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiUnauthorizedResponse } from '@nestjs/swagger';

export function Auth(...roles: string[]) {
  return applyDecorators(
    UseGuards(JwtAuthGuard, RolesGuard),
    Roles(...roles),
    ApiBearerAuth(),
    ApiUnauthorizedResponse({ description: 'unauthorized' }),
  );
}

Usage:

@Auth('admin')
@Get('users')
listUsers() { ... }

Reduces decorator stack noise when 4+ decorators repeat.

Anti-patterns

  • ❌ Using Reflect.getMetadata(...) directly — use Reflector.get() (NestJS API). It handles inheritance correctly.
  • ❌ @Body('field') instead of a typed DTO — bypasses class-validator, no type safety.
  • ❌ Injecting @Res() then forgetting passthrough: true — breaks interceptors.
  • ❌ Multiple class-level @UseGuards(A) @UseGuards(B) — last one wins; combine into one: @UseGuards(A, B).
  • ❌ Custom decorator without preserving type info — declare return type explicitly.
  • ❌ SetMetadata('key', val) inline at the route — make a named decorator (Roles(...)) so it's discoverable.
  • ❌ @Controller('/users/') — no leading or trailing slash; Nest adds them.

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/nestjs-decorator-patterns-mvda897w/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/nestjs-decorator-patterns-mvda897w' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/nestjs-decorator-patterns-mvda897w/download' --output '.skill-downloads/nestjs-decorator-patterns-mvda897w/SKILL.md.part' && mv '.skill-downloads/nestjs-decorator-patterns-mvda897w/SKILL.md.part' '.skill-downloads/nestjs-decorator-patterns-mvda897w/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/nestjs-decorator-patterns-mvda897w/SKILL.md' && test -s '.skill-downloads/nestjs-decorator-patterns-mvda897w/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/decorator-patterns' && cp -R '.skill-downloads/nestjs-decorator-patterns-mvda897w' '.claude/skills/decorator-patterns'

Cursor
test -f '.skill-downloads/nestjs-decorator-patterns-mvda897w/SKILL.md' && test -s '.skill-downloads/nestjs-decorator-patterns-mvda897w/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/decorator-patterns' && cp -R '.skill-downloads/nestjs-decorator-patterns-mvda897w' '.cursor/skills/decorator-patterns'

Codex
test -f '.skill-downloads/nestjs-decorator-patterns-mvda897w/SKILL.md' && test -s '.skill-downloads/nestjs-decorator-patterns-mvda897w/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/decorator-patterns' && cp -R '.skill-downloads/nestjs-decorator-patterns-mvda897w' '.agents/skills/decorator-patterns'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/nestjs-decorator-patterns-mvda897w'

openskills read 'nestjs-decorator-patterns-mvda897w'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/nestjs-decorator-patterns-mvda897w/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills