Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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/

like image 984
Daniel Delgado Avatar asked Oct 19 '25 15:10

Daniel Delgado


1 Answers

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

like image 157
Jay McDoniel Avatar answered Oct 21 '25 03:10

Jay McDoniel