hardywang
hardywang

Reputation: 5172

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?

Upvotes: 63

Views: 106905

Answers (2)

zemil
zemil

Reputation: 5084

Implementation of @Headers decorator. This can help you to create your own custom decorators:

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

const Header = createParamDecorator((name: string, ctx: ExecutionContext): string | undefined => {
    const req = ctx.switchToHttp().getRequest<IncomingMessage>();
    const { headers } = req;

    return headers[name] as string;
});

If you want to create a custom decorator based on Headers:

const IsMobileClient = createParamDecorator((_: never, ctx: ExecutionContext): boolean => {
    const req = ctx.switchToHttp().getRequest<IncomingMessage>();
    const isMobile = req.headers['user-agent']?.toLowerCase().includes('mobi');

    return Boolean(isMobile);
});

And usage example:

@Get()
public async yourRequest(
    @Headers('cookie') cookie?: string,
    @IsMobileClient() isMobile: boolean,
): Promise<any> {
    console.log(cookie, isMobile);
    // ...other code
}

Upvotes: 5

Kim Kern
Kim Kern

Reputation: 60457

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.

Upvotes: 114

Related Questions