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

Making onProxyRes function asynchronous friendly

Open rainb3rry opened this issue 1 year ago • 2 comments

I would like to be able to set response after a specific time passed as my code below, but it's not possible.

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();

const asyncFunc = () => {
  return new Promise((resolve) => {
    setTimeout(() => resolve("Hello World!"), 3000)
  })
}


const onProxyRes = async function  (proxyRes, req, res) {


  const result = await asyncFunc()

  res.write(result);
  res.end();

};


const exampleProxy = createProxyMiddleware({
  target: 'https://example.com',
  changeOrigin: true,
  on: { proxyRes: onProxyRes }
});
app.use('/', exampleProxy);



app.listen(3003)

But if I remove const result = await asyncFunc() part, I can set response anything I want inside of res.write();.

rainb3rry avatar Nov 18 '24 10:11 rainb3rry

if you remove the const result = await asyncFunc() the request will not pass to the backend and the function will no longer wait for the async() to finish. instead of that always use await() when using async().

ravin00 avatar Nov 28 '24 18:11 ravin00

I did something similar with proxyReqWS in https://github.com/http-party/node-http-proxy/pull/1709 you can easily adapt for your needs

r4id4h avatar Aug 11 '25 17:08 r4id4h