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

Request terminates in middleware. How to call next middleware in stack?

Open hpl002 opened this issue 4 years ago • 2 comments

Request terminates in middleware. There is however an option "option.onProxyRes" that allows you to further handle the request as you wish in the onProxyRes handler.

However, this handler only takes proxyRes, req, res as args. How may i then call the next middleware in my stack?

Excerpt from readme:

function onProxyRes(proxyRes, req, res) {
  proxyRes.headers['x-added'] = 'foobar'; // add new header to response
  delete proxyRes.headers['x-removed']; // remove header from response
}

Fairly new to express so please excuse me if this is a silly question..

Thanks!

hpl002 avatar Jan 05 '21 10:01 hpl002

Provided a middleware stack where i want to perform additional operations on the response.

E.g.:

app.use(baseUrl, (req, res, next) => {
      console.log("before");
      return next();
    })      
     app.use(baseUrl, apiProxy);      
     app.use(baseUrl, (req, res, next) => {
      console.log("after");
      return res.end();
    })      

Request terminates in proxy middleware. "after" is therefore never logged.

Example scenario
Say you have a middleware stack that looks like this:

  1. auth
  2. request validation
  3. proxy
  • here i might add additional event handlers to format my request before going out and perhaps the response as well
  1. response validation
  2. other middleware
  3. some more middleware
  4. return response to client

The current specification terminates the request once a response has been returned from proxy. Meaning that steps 4-7 are effectively ignored. From what i have read there is seemingly no way to pass the response to the next middleware.

What would be the correct approach to a problem like this?

Possible solutions

  1. Move remaining middleware into the onProxyRes event handler.

Requires a fair bit of hackery as the subsequent middlewares are not called as expexted (via next()). Not even sure that this would work

  1. Create a completely independent express instance which only handles the proxying. Wrap this in its own middleware and append to the "outer" express instance.

Could seemingly work. Might have to do some intelligent merging of responses.

I will try to solve this using the latter solution.

hpl002 avatar Jan 05 '21 11:01 hpl002

Duplicate of #248

hpl002 avatar Jan 06 '21 08:01 hpl002