maxshuty
maxshuty

Reputation: 10672

Proxying to different dynamic domains in a VueJS app

In our VueJS app I have a URL that is returned from an API that points to amer.example.com/put/stuff that I need to PUT some data.

Obviously when I do this PUT I get CORS errors. To remedy this I have a devServer proxy setup that says to reroute all /put/stuff to go through example.com like this:

devServer: {
  port: 9034,
  proxy: {
    '/put/stuff': {
      target: 'amer.example.com',
    },
  },
},

Voila, things start working again.

However, the URL that is returned from the API is dynamic and can be pointing to yet another region like EMEA, emea.example.com/put/stuff but everything else in the URL is the exact same.

How can I make the proxy dynamic so that it will go to amer.example.com, emea.example.com, or any other region based on the URL I get back from another API.

I have no control over the other API and how the URL that is returned is shaped.

Upvotes: 0

Views: 863

Answers (1)

maxshuty
maxshuty

Reputation: 10672

The only way that I can think of to do this would be ugly, but it should work.

TLDR

Insert the region into the path of the URL you get back from the API, and then look for that path in the proxy. Finally use pathRewrite in your proxy to remove it from the URL.

Longer explanation

Create a new function in your methods that inserts the region into the URL path, like this:

methods: {
  insertRegionIntoUrlPath(urlStr) {
    const url = new URL(urlStr);

    // Grab the region from the url, if it includes 'https://' then update the substring obviously).
    const regionPath = `/${url.hostname.substring(0,4)}`;

    // Set the path to now include the region in the beginning
    url.pathname = `${regionPath}${url.pathname}`;

    // Return the full URL that now contains the region: `https://amer.example.com/amer/put/stuff`
    return url.href;    
  },
}

You would then use this function wherever that PUT is happening to add the region into the URL path.

I've made an assumptions that your region is always 4 characters long, if that could be different then just use some regex to pull the subdomain out.

Then in your proxy setup you can now target the specific region paths you want and remove the part of the path you added, like this:

module.exports = {
  devServer: {
    proxy: {
      '/amer': {
        target: 'https://amer.example.com',
        pathRewrite: {'^/amer' : ''} // Removing `/amer` from the path
      },
      '/emea': {
        target: 'https://emea.example.com/',
        pathRewrite: {'^/emea' : ''} // Removing `/emea` from the path
      }
    }
  }
};

So now what you have done is got a URL from the API, added the region into the path and made a PUT request and finally the proxy picks up these requests because they will match the region paths like /amer and then we simply have the proxy remove that part from the URL before the request is sent off.

Upvotes: 1

Related Questions