node-http-proxy icon indicating copy to clipboard operation
node-http-proxy copied to clipboard

async handler for proxyReqWs

Open LiranBri opened this issue 6 years ago • 2 comments

Hello, Because proxyReqWs event is fired by event emitter [code], it does not support any async handling by returning a promise.

When someone tries to provide an async function handler that modifies headers, it results by an exception that the headers are modified AFTER the response has been sent.

Its big brother, proxyReq, has no such problem.

Is there any workaround or suggested way to make a modification that involves async operation?

if not, I would suggest such a feature.. even though it might require changing how the mechanism works (top of my head: optional parameters such as "next" + configuration to hint its async somehow).

Moreover, I would suggest to explicitly document the fact that an async handler is not allowed.

LiranBri avatar Dec 05 '19 07:12 LiranBri

I created a Fork with a modification that supports async handling, without breaking compatibility. maintainers, would you like a PR?

https://github.com/LiranBri/node-http-proxy

my trick is to pass an asyncContext and use it like this:

onProxyReqWs: (proxyReq, req, socket, options, head, asyncContext) =>
      asyncContext(async () => {
        // code ...
        await whatever()
        // code ...
        proxyReq.setHeader('key', 'value')
      }),

LiranBri avatar Dec 08 '19 08:12 LiranBri

I had the same problem but came up with a different solution which doen't need a new parameter. I didn't write any tests feel free to use. https://github.com/http-party/node-http-proxy/pull/1709

r4id4h avatar Aug 11 '25 18:08 r4id4h