Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

httpProxyMiddleware chaining with multipel targets #52

Open
wansiedler opened this issue Dec 22, 2021 · 1 comment
Open

httpProxyMiddleware chaining with multipel targets #52

wansiedler opened this issue Dec 22, 2021 · 1 comment
Assignees
Labels
good first issue Good for newcomers help wanted Extra attention is needed question Further information is requested

Comments

@wansiedler
Copy link

It would be great to have the possibility to chain proxy middlewares like this:
httpProxyMiddleware(req, res, {
target: process.env.target1,
pathRewrite: [{
patternStr: "^/api", replaceStr: "",
}],
}).than((response)=>httpProxyMiddleware(req, response, {
target: process.env.target2,
pathRewrite: [{
patternStr: "^/s3", replaceStr: "",
}],
}))
What is the proper way of doing this?

@stegano stegano self-assigned this Dec 23, 2021
@stegano stegano added good first issue Good for newcomers help wanted Extra attention is needed question Further information is requested labels Dec 23, 2021
@stegano
Copy link
Owner

stegano commented Dec 23, 2021

Hi @wansiedler
It seems to be possible to use multiple targets by implementing it like the code below.

export default (req: NextApiRequest, res: NextApiResponse) => {
  const proxyOptions = [{
      target: 'https://www.example1.com',
      pathRewrite: [{
        patternStr: '^/api/new',
        replaceStr: '/v2'
      }, {
        patternStr: '^/api',
        replaceStr: ''
      }],
    },{
      target: 'https://www.example2.com',
      pathRewrite: [{
        patternStr: '^/api/new',
        replaceStr: '/v2'
      }, {
        patternStr: '^/api',
        replaceStr: ''
      }],
    }];

  const proxyOption = proxyOptions.find(({pathRewrite}) => {
    return pathRewrite.some(({patternStr}) => RegExp(patternStr).test(req?.url))
  })

  if(proxyOption) {
    return httpProxyMiddleware(req, res, proxyOption)
  } else {
    return res.status(404).send(null);
  }
};

Thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good first issue Good for newcomers help wanted Extra attention is needed question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants