Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a request header using NestJS?

Tags:

nestjs

I have a simple app that returns Something: Value as a header. I currently have the following as a controller...

import { Controller, Get, Header } from "@nestjs/common";

@Controller("health")
export class HealthController {
  @Get()
  @Header("content-type", "application/json")
  checkHealth(): unknown {
    return {
      test: "This is the test",
    };
  }
}

In express I would expect to be able to do something like req.headers but I am not sure how to do that in nestjs.

like image 447
Jackie Avatar asked Aug 27 '26 14:08

Jackie


1 Answers

You should pass Headers from @nestjs/common as an argument to function:

import { Controller, Get, Headers } from "@nestjs/common";

@Controller("health")
export class HealthController {
  @Get()
  checkHealth(@Headers() headers: Record < string, string > ) {
    return {
      test: "This is the test",
    };
  }
}

If you need just one header you can pass it's name to header like this: @Headers('content-type') headers: string.

Alternatively if you want access to express req object you can also pass it to your controller

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

@Controller("health")
export class HealthController {
  @Get()
  checkHealth(@Req() req: Request) {
    return {
      test: "This is the test",
    };
  }
}
like image 136
ruciu Avatar answered Sep 03 '26 23:09

ruciu