Search code examples
node.jshttp-headersnestjs

How to use Nest.js's @Headers properly?


According to the controller docs I can use @Headers(param?: string) or req.headers or req.headers[param] to get header value. I tried the first approach, I have following in my request headers from Postman

Content-Type:application/json
My-Id:test12345

I have following controller sample code

@Put('/aa/:aa/bb/:bb/')
@UsePipes(new ValidationPipe({ transform: true }))
public async DoMyJob(@Body() request: MyRequestDto,
                                @Param('aa') aa: number,
                                @Param('bb') bb: string,
                                @Headers('My-Id') id: string): Promise<MyResponseDto> {
    // More code here
}

When I set break point to inspect the value from My-Id header it is undefined.

So how shall I do in Nest.Js properly to get the header value from RESTful service client?


Solution

  • Headers will be sent in lower case so you need @Headers('my-id') instead.


    Easy to debug by injecting the full headers object:

    import { Headers } from '@nestjs/common';
    ...
    @Put('/')
    public async put(@Headers() headers) {
        console.log(headers);
    }
    

    The headers variable will then refer to the req.headers.