How can I set a header field in a response with NestJS?

Viewed 21910

I'm trying:

    @Post('login')
    async login(@Body() body: AuthDto, @Res() res: Response) {
        const loginResponse = await this.authService.login(body);
        console.log('loginResponse', loginResponse)
        res.headers.set('x-access-token', loginResponse.access_token)
        return loginResponse
    }

but no dice. I get an error:

TypeError: Cannot read property 'set' of undefined
3 Answers

Not the most elegant way: return res.set({ 'x-access-token': loginResponse.access_token }).json(loginResponse);

I'd separate this logic into an interceptor, checking if the response is valid for path /login, if so return the correct header (using some value from loginResponse)

import { Controller, Get, Response } from '@nestjs/common';
import { Response as Res } from 'express';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(@Response() res: Res): Res {
    return res.set({ 'x-access-token': 1 }).json({ hello: 'world' });
  }

  @Get()
  getHelloAlt(@Response() res) {
    return res.set({ 'x-access-token': 1 }).json({ hello: 'world' });
  }
}

This is my working version, notice the Express Response and not Nest.js.

EDIT: The type imported from Nest.js/common is a decorator function, instead either use no type, or import Response from Express.js.

To specify a custom response header, you can either use a @Header() decorator or a library-specific response object (and call res.header() directly).

Import Header from the @nestjs/common package.

@Post()
@Header('Cache-Control', 'none')
create() {
  return 'This action adds a new cat';
}

I use an interceptor. As I want to add a field to the headers on the response indicating my service, I also set this as a global interceptor, but you can use it by route as well.

response-add-access-token-to-header.interceptor.ts

import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';

import { Response as ExpressResponse } from 'express';

@Injectable()
export class ResponseAddAccessTokenToHeaderInterceptor implements NestInterceptor {
    intercept(context:ExecutionContext, next:CallHandler): Observable<any> {

        const ResponseObj:ExpressResponse = context.switchToHttp().getResponse();
        ResponseObj.setHeader('x-access-token', 'Your Data' );
        return next.handle();
    }
}

To add it globally, adjust main.ts:

async function bootstrap() {
    const app = await NestFactory.create(AppModule);
    app.useGlobalInterceptors(new ResponseAddAccessTokenToHeaderInterceptor());
    await app.listen(8080);
}
bootstrap();
Related