fastify / fastify-http-proxy

Proxy your http requests to another server, with hooks.
MIT License
338 stars 91 forks source link

Is it possible to use `preSerialization` or `onSend` hooks for fastify/http-proxy? #340

Closed nducal closed 7 months ago

nducal commented 7 months ago

Prerequisites

Issue

Hello!

While reading the documentation for fastify/http-proxy, I haven't found the possibility to set a preSerialization or onSend hooks for a proxy. I know I can set onResonse for reply-from, but from the fastify documentation, I have read that after this you cannot send any more data to client (i.e. when you get to onResponse, the client already got the response and this is useful only for some parsing or sending some stats etc.).

What i want to achieve is have something like this:

fastify.register(FastifyHttpProxy, {
  upstream: "http://localhost:8080",
  prefix: '/',
  http2: false,
  preHandler: preProcessRequest,
  preSerialization: preProcessResponse
})

where preSerialization would change some things in the response from the upstream (this has to be done to protect some credentials/other editing which I can't do in the upstream service).

Is there a good way to make this work as I intend it to?

mcollina commented 7 months ago

I don't think we are wiring those hooks.

You can achieve this by wrapping addHook and fastifyhttproxy in a encapsulating plugin.

nducal commented 7 months ago

Hi @mcollina! Thank you for your response. Yeah, there is no wiring for those hooks after analyzing the code for http-proxy. Also, could you provide a short example for encapsulating plugin? Or if there are any examples available online

mcollina commented 7 months ago
fastify.register(async function (fastify) {
  fastify.addHook(...)
  fastify.register(require('@fastify/http-proxy', ...)
})
nducal commented 7 months ago

Oh, got it. Thank you!