0Pricing
NestJS Enterprise Backend APIs · 강의

매개변수 데코레이터로 요청 컨텍스트 읽기

createParamDecorator와 ExecutionContext를 사용해 사용자 지정 @CurrentUser 및 @ClientIp 매개변수 데코레이터를 만듭니다

매개변수 데코레이터로 요청 컨텍스트 읽기은(는) CoddyKit의 무료 NestJS Enterprise Backend APIs 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 NestJS Enterprise Backend APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. NestJS Enterprise Backend APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Param Decorators?

In NestJS controllers, you often need to pull the same piece of data out of the request over and over: the authenticated user, the client IP, a tenant id from a header. Doing this with @Req() and digging into request.user in every handler is repetitive and leaks framework details into your business logic.

Custom param decorators let you encapsulate that extraction once and reuse it everywhere:

  • @CurrentUser() instead of req.user
  • @ClientIp() instead of parsing x-forwarded-for

The result is cleaner, more testable, and more declarative controller code.

The Repetitive Way

Here is what you usually start with: grabbing the whole request object and reaching into it manually. It works, but every handler repeats the same lines, and the controller now knows about request.user, which is an implementation detail of your auth guard.

Notice how the actual route logic is buried under plumbing. This is exactly what a param decorator removes.

import { Controller, Get, Req } from '@nestjs/common';
import { Request } from 'express';

@Controller('profile')
export class ProfileController {
  @Get()
  getProfile(@Req() request: Request) {
    const user = (request as any).user;
    return { id: user.id, email: user.email };
  }
}

createParamDecorator

NestJS exposes the factory createParamDecorator from @nestjs/common. You give it a function that receives two arguments and returns whatever value you want injected into the handler parameter.

  • data — the optional argument passed when the decorator is used, e.g. @CurrentUser('email').
  • ctx: ExecutionContext — a wrapper around the current request context, independent of the transport (HTTP, RPC, WebSocket).

The returned value becomes the parameter's value at call time.

import { createParamDecorator, ExecutionContext } from '@nestjs/common';

export const Example = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    // return any value -> it gets injected into the param
    return 'hello';
  },
);

Getting the HTTP Request

For HTTP apps you convert the generic ExecutionContext into an HTTP-specific argument host and read the request from it:

  • ctx.switchToHttp() returns an HttpArgumentsHost.
  • .getRequest() gives you the underlying request (Express or Fastify).

Using switchToHttp() keeps the decorator explicit about which transport it targets. The same context could also be switched to RPC or WS for other protocols.

import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { Request } from 'express';

export const RawRequest = createParamDecorator(
  (data: unknown, ctx: ExecutionContext): Request => {
    return ctx.switchToHttp().getRequest<Request>();
  },
);

Building @CurrentUser

Assume an auth guard (e.g. a JWT strategy) has already attached the authenticated user to request.user. The @CurrentUser() decorator simply returns it.

This is the canonical pattern in enterprise NestJS apps: the guard does authentication, and the decorator gives ergonomic access to the result without exposing the request object.

import { createParamDecorator, ExecutionContext } from '@nestjs/common';

export interface AuthUser {
  id: string;
  email: string;
  roles: string[];
}

export const CurrentUser = createParamDecorator(
  (data: unknown, ctx: ExecutionContext): AuthUser => {
    const request = ctx.switchToHttp().getRequest();
    return request.user;
  },
);

Using the data Argument

The first parameter, data, is what the caller passes inside the decorator's parentheses. You can use it to return a single property instead of the whole object:

  • @CurrentUser() returns the full user.
  • @CurrentUser('email') returns just the email.

Type the data argument as keyof AuthUser so the caller gets autocomplete and compile-time safety on the property name.

import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { AuthUser } from './auth-user.interface';

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

Consuming @CurrentUser in a Controller

Now the controller reads beautifully. The guard guarantees the user exists; the decorator injects exactly what each handler needs. No @Req(), no manual property digging.

This separation is what makes the handler easy to unit-test: you just call the method with a plain user object.

import { Controller, Get, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from './jwt-auth.guard';
import { CurrentUser } from './current-user.decorator';
import { AuthUser } from './auth-user.interface';

@UseGuards(JwtAuthGuard)
@Controller('me')
export class MeController {
  @Get()
  getMe(@CurrentUser() user: AuthUser) {
    return user;
  }

  @Get('email')
  getEmail(@CurrentUser('email') email: string) {
    return { email };
  }
}

Building @ClientIp

Behind a load balancer or reverse proxy, the real client IP is not request.ip but the first entry of the x-forwarded-for header. A @ClientIp() decorator centralizes this logic so every handler reads the correct address.

Important: only trust x-forwarded-for when you actually run behind a trusted proxy, and enable Express's trust proxy setting. Otherwise clients can spoof the header.

import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { Request } from 'express';

export const ClientIp = createParamDecorator(
  (data: unknown, ctx: ExecutionContext): string => {
    const request = ctx.switchToHttp().getRequest<Request>();
    const forwarded = request.headers['x-forwarded-for'];
    if (typeof forwarded === 'string' && forwarded.length > 0) {
      return forwarded.split(',')[0].trim();
    }
    return request.ip ?? '';
  },
);

Pure Extraction Logic Is Testable

The valuable part of a param decorator is its pure extraction logic. You can lift that into a plain function, unit-test it with a fake request, and call it from the decorator. Here is the IP-parsing logic as a standalone, runnable program.

This demonstrates the rule for choosing the first forwarded address and the fallback behavior — no NestJS or server required to verify it.

function extractClientIp(headers: Record<string, string>, fallbackIp: string): string {
  const forwarded = headers['x-forwarded-for'];
  if (typeof forwarded === 'string' && forwarded.length > 0) {
    return forwarded.split(',')[0].trim();
  }
  return fallbackIp;
}

console.log(extractClientIp({ 'x-forwarded-for': '203.0.113.7, 70.41.3.18' }, '10.0.0.1'));
console.log(extractClientIp({}, '10.0.0.1'));
console.log(extractClientIp({ 'x-forwarded-for': '198.51.100.5' }, '10.0.0.1'));

Combining Decorators in One Handler

Param decorators compose freely. A single handler can mix built-in decorators (@Body, @Param) with your custom ones. NestJS resolves each parameter independently by its decorator metadata.

Here an audit endpoint records who did what and from where, reading the user and IP declaratively.

import { Controller, Post, Body, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from './jwt-auth.guard';
import { CurrentUser } from './current-user.decorator';
import { ClientIp } from './client-ip.decorator';
import { AuthUser } from './auth-user.interface';

@UseGuards(JwtAuthGuard)
@Controller('audit')
export class AuditController {
  @Post('action')
  record(
    @CurrentUser('id') userId: string,
    @ClientIp() ip: string,
    @Body() body: { action: string },
  ) {
    return { userId, ip, action: body.action, at: new Date().toISOString() };
  }
}

Validation and Pipes Still Apply

A custom param decorator returns a raw value, so you can still attach pipes to it just like built-in decorators. Pass a pipe as an extra argument when using the decorator.

  • @CurrentUser('id', ParseUUIDPipe) validates that the extracted id is a UUID.
  • Pipes run after the decorator factory returns its value.

This lets you keep extraction and validation cleanly separated while still benefiting from NestJS's pipe pipeline.

import { Controller, Get, ParseUUIDPipe } from '@nestjs/common';
import { CurrentUser } from './current-user.decorator';

@Controller('orders')
export class OrdersController {
  @Get('mine')
  myOrders(@CurrentUser('id', ParseUUIDPipe) userId: string) {
    return { userId };
  }
}

Quick Check

Test your understanding of how a custom param decorator reads the request.

Recap

You learned to read request context declaratively with custom param decorators:

  • createParamDecorator((data, ctx) => ...) builds a reusable decorator; the returned value is injected into the handler parameter.
  • ctx.switchToHttp().getRequest() retrieves the HTTP request in a transport-explicit way.
  • @CurrentUser() wraps request.user (populated by your auth guard) and can return a single property via the data argument typed as keyof AuthUser.
  • @ClientIp() centralizes x-forwarded-for parsing, with a fallback to request.ip — trust the header only behind a real proxy.
  • Keep extraction logic pure so it is easy to unit-test, and remember you can still chain pipes like ParseUUIDPipe onto your custom decorators.

자주 묻는 질문

“매개변수 데코레이터로 요청 컨텍스트 읽기” 강의는 무료인가요?

네 — “매개변수 데코레이터로 요청 컨텍스트 읽기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 NestJS Enterprise Backend APIs 강의 전체를 잠금 해제할 수 있습니다. NestJS Enterprise Backend APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

“매개변수 데코레이터로 요청 컨텍스트 읽기”에서 뭘 배우나요?

createParamDecorator와 ExecutionContext를 사용해 사용자 지정 @CurrentUser 및 @ClientIp 매개변수 데코레이터를 만듭니다 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

NestJS Enterprise Backend APIs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 NestJS Enterprise Backend APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“매개변수 데코레이터로 요청 컨텍스트 읽기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 NestJS Enterprise Backend APIs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 NestJS Enterprise Backend APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 매개변수 데코레이터로 요청 컨텍스트 읽기
  2. SetMetadata와 Reflector로 메타데이터 연결하기
  3. applyDecorators로 데코레이터 조합하기
  4. 공통 설정을 위한 클래스 수준 데코레이터
← NestJS Enterprise Backend APIs(으)로 돌아가기