Nest: Validate Headers

Created on 13 May 2020  路  2Comments  路  Source: nestjs/nest

It will be useful to validate headers along with all Body, Query etc. Is not always about keys and tokens so that you use a guard, there can also be other values that you want to use in headers for some methods. Taking advantage of class-validator, transforms and DTO that nestjs is promoting

@Headers("x-lang", LangPipe, CustomValidationPipe) langDto LangDto;

Thanks

needs triage type

Most helpful comment

Leaving it here in case someone needs it. As said by @kamilmysliwiec , a custom decorator can be used for validating the headers. (In the same way we validate req body ! )

request-header.decorator.ts

import { createParamDecorator, ExecutionContext } from '@nestjs/commom'
import { plainToClass } from 'class-transformer';
import { ClassType } from 'class-transformer/ClassTransformer';
import { validateOrReject } from 'class-validator';

export const RequestHeader = createParamDecorator(
  async (value:  ClassType<unknown>, ctx: ExecutionContext) => {

    // extract headers
    const headers = ctx.switchToHttp().getRequest().headers;

    // Convert headers to DTO object
    const dto = plainToClass(value, headers, { excludeExtraneousValues: true });

    // Validate 
    await validateOrReject(dto);

    // return header dto object 
    return dto;
  },
);

Define your header dto according to the headers which would be coming

header.dto.ts

import { IsDefined, IsString } from "class-validator";

export class HeaderDTO {
    @IsString()
    @IsDefined()
    @Expose({ name: 'myheader1' })        // required as headers are case insensitive
    myHeader1: string;

    @IsString()
    @IsDefined()
    @Expose({ name: 'myheader1' })
    myHeader2: string;
}

Finally use it as a method param and pass the dto you want to validate against :)

 @Get('/hello')
 getHello(@RequestHeader(HeaderDTO) headers: any) {
        console.log(headers);
    }
}

All 2 comments

Leaving it here in case someone needs it. As said by @kamilmysliwiec , a custom decorator can be used for validating the headers. (In the same way we validate req body ! )

request-header.decorator.ts

import { createParamDecorator, ExecutionContext } from '@nestjs/commom'
import { plainToClass } from 'class-transformer';
import { ClassType } from 'class-transformer/ClassTransformer';
import { validateOrReject } from 'class-validator';

export const RequestHeader = createParamDecorator(
  async (value:  ClassType<unknown>, ctx: ExecutionContext) => {

    // extract headers
    const headers = ctx.switchToHttp().getRequest().headers;

    // Convert headers to DTO object
    const dto = plainToClass(value, headers, { excludeExtraneousValues: true });

    // Validate 
    await validateOrReject(dto);

    // return header dto object 
    return dto;
  },
);

Define your header dto according to the headers which would be coming

header.dto.ts

import { IsDefined, IsString } from "class-validator";

export class HeaderDTO {
    @IsString()
    @IsDefined()
    @Expose({ name: 'myheader1' })        // required as headers are case insensitive
    myHeader1: string;

    @IsString()
    @IsDefined()
    @Expose({ name: 'myheader1' })
    myHeader2: string;
}

Finally use it as a method param and pass the dto you want to validate against :)

 @Get('/hello')
 getHello(@RequestHeader(HeaderDTO) headers: any) {
        console.log(headers);
    }
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

breitsmiley picture breitsmiley  路  3Comments

artaommahe picture artaommahe  路  3Comments

rlesniak picture rlesniak  路  3Comments

marshall007 picture marshall007  路  3Comments

mishelashala picture mishelashala  路  3Comments