Fastify & NestJS - How to set response headers in interceptor

Viewed 3340

I'm trying to set the response headers in my interceptor, and have had no luck with any method I've found yet. I've tried:

 const request = context.switchToHttp().getRequest();
 const response = context.switchToHttp().getResponse();
 <snippet of code from below>
 return next.handle();
  • request.res.headers['my-header'] = 'xyz'
  • response.header('my-header', 'xyz')
  • response.headers['my-header'] = 'xyz'
  • response.header['my-header'] = 'xyz'

with no luck. The first option says that res is undefined, the second "Cannot read property 'Symbol(fastify.reply.headers)' of undefined", and the others just do nothing.

1 Answers

I have the following working for me with the FastifyAdapter in my main.ts:

HeaderInterceptor

@Injectable()
export class HeaderInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      tap(() => {
        const res = context.switchToHttp().getResponse<FastifyReply<ServerResponse>>();
        res.header('foo', 'bar');
      })
    );
  }
}

Using .getResponse<FastifyReply<ServerResponse>>() gives us the correct typings to work with.

AppModule

@Module({
  imports: [],
  controllers: [AppController],
  providers: [
    AppService,
    {
      provide: APP_INTERCEPTOR,
      useClass: HeaderInterceptor,
    },
  ],
})
export class AppModule {}

Bind the interceptor to the entire server

curl Command

▶ curl http://localhost:3000 -v
* Rebuilt URL to: http://localhost:3000/
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 3000 (#0)
> GET / HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.54.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< foo: bar
< content-type: text/plain; charset=utf-8
< content-length: 12
< Date: Thu, 14 May 2020 14:09:22 GMT
< Connection: keep-alive
< 
* Connection #0 to host localhost left intact
Hello World!% 

As you can see, the response comes back with the header foo: bar meaning the interceptor added what was expected.

Looking at your error, it looks like your second attempt may have actually been response.headers('my-header', 'xyz). Whatever the case, the above is working for me on a nest new application, and on the latest version of Nest's packages.

Related