Can @Headers in Nest.js be validated through DTOs?

99 Views Asked by At

I am new to Nest.js and have a good understanding of the overall syntax. However, while creating one of the controllers, I encountered an issue related to the validation of data parsed by the @Headers decorator. For example

@Get('endpoint')
  myEndpoint(@Headers() headers: HeaderDto): string {
    ....
  }

validation under HeaderDto works perfectly fine with @Body() decorator.

I tried to Google it and found that it has something to do with a structural issue in headers, but I don't fully understand what this means.

1

There are 1 best solutions below

0
Jay McDoniel On BEST ANSWER

Yes, but you have to create your own @Headers() parameter decorator because the one provided by Nest will be skipped by pipes not explicitly applied to the decorator. This is done purposefully, as there can, and most likely will, be more headers than the DTO specifies, and more often than not people like to set things like forbidNonWhitelistProperites which would cause errors for unexpected headers.

To create your own @Headers() it's a simple call to createParamDecorators

export const Headers = createParamDecorator((data: string | undefined, ctx: ExecutionContext) => {
  const req = ctx.switchToHttp().getRequest();
  if (data) {
    return req.headers[data];
  }
  return req.headers;
});