How to get/set request/response header in middelware [Nest Fastify]?

7.1k views Asked by At

How to inject a request header in NestJS using Fastify.

import { FastifyRequest, FastifyReply } from 'fastify'; // fastify types are not valid

@Injectable()
export class TracingMiddleware implements NestMiddleware {
  use(req: any, res: any, next: () => void) {
    console.log('MyRequestHeaderKey', req.headers['MyRequestHeaderKey']); // find out how to get a header 
    res.header('MyResponseHeaderKey', 'MyResponseHeaderValue'); // find out how to set headers
    next();
  }
}

There is no reference for fastify middleware on nest docs: https://docs.nestjs.com/middleware

I have read fastify doc without success: https://www.fastify.io/docs/v1.13.x/Reply/ & https://www.fastify.io/docs/v1.13.x/Request/

1

There are 1 answers

3
Jay McDoniel On BEST ANSWER

Middleware with Nest is Express-style middleware. While it is possible to work with Fastify, do note that you're essentially accessing req.raw and res.raw instead of FastifyRequest and FastifyReply. Guards and interceptors are usually more successful at working with Fastify than standard middleware are, as a heads up.

With all that said, req.headers should pull back the headers property on the Incoming Request, and res.setHeader() should be used for setting a header on the ServerResponse