Different proxy config based on environment in Angular 2 CLI

Tu Shams picture Tu Shams · Aug 5, 2017 · Viewed 8.8k times · Source

How can I declare 2 different proxy URLs for development and production environments in Angular 2 CLI project? For example, while in development mode, I would like to use

{
    "/api/*": {
        "target": "http://localhost:3000",
        "secure": false
    }
}

but in production mode, I will use

{
    "/api/*": {
        "target": "http://api.exampledomain.com",
        "secure": false
    }
}

Answer

LE GALL Benoît picture LE GALL Benoît · Mar 24, 2018

in fact, you can do it, you just need to configure the router :

{
    "/api": {
        "target": "https://api.exampledomain.com",
        "secure": false,
        "logLevel": "debug",
        "router": {
          "localhost:4200" : "http://localhost:3000/exampledomain",
          "staging.exampledomain.com" : "http://api.staging.exampledomain.com"
        }
    }
}

What this do :

  • yout url match the proxy => will call the target defined
  • the host url match one router configuration => use the new target

For example :

I've deployed on localhost:4200 my angular app, when calling the url "api/callMeMaybe", then the router detect it and redirect in "http://localhost:3000/exampledomain".
If I've been on staging.exampledomain.com then the redirection will have be to "http://api.stagging.exampledomain.com".
Then, if none match, it keep the original target redirection.

Be careful, as order matters (the 1st match will be take)

Here is the documentation with an example

Edit

You can find the host value on your chrome debugger Network tab and selecting the api call, you get this details : api call header screenshot