node.jsinterceptorfastify

How to get the body of a Request in OnResponse hook of Fastity Reply From


I am using Fastify HTTP proxy in a service that act as a proxy that needs to inspect specific requests/response in the interaction between a client and a target server. I found this solution that uses the onResponse hook:

const fastifyProxyLib = require("@fastify/http-proxy");

register(fastifyProxyLib, {
        ...proxyConfig, //some config
        upstream, //some url
        preHandler: async ({ url, body }) => {
          //Do something for specific url and body
        }
        replyOptions: {
          onResponse: (request, reply, res) => {
            console.log(res);
            reply.code(200).send(res);
          },
        }, 
}

Everything works well but I am not able to get the body of res in order to inspect what's inside its payload. The response correctly gets to the client where I use axios and I am able to see the correct body. Inside reply.body I got the body of the initial request instead. How can I inspect the res?


Solution

  • The res argument is a stream, so you need to consume it:

        onResponse: (request, reply, res) => {
          let data = '';
          res.on('data', chunk => {
            data += chunk;
          })
          res.on('end', () => {
            console.log('data is: ' + data);
            reply.code(200).send(data);
          })
        },
    

    Adding an onResponse hook should work as well, without the need to consume the res object. https://www.fastify.io/docs/latest/Reference/Hooks/#onresponse