'Angular CLI Proxy with env variables

I need to create a proxy to my backend server in order to communicate with it. I've already succesfully set this up, but now I have 2 places where I need to change variables when changing the environment.

My versions:

  • Angular CLI 7.0.6
  • Angular 7.1.0

NOTE: I have the proxy working (see Angular docs for the setup), I only want to improve the setup.


Proxy.conf.js

This is my current (and working!) config.js

const PROXY_CONFIG = {
  "/api/*": {
    "target": "https://url.to.somewhere/",
    "logLevel": "debug",
    "changeOrigin": true
  }
};

module.exports = PROXY_CONFIG;

What I would like it to combine this file with the Angular environment.ts file.


What I want

I would like to use the variables from the environment.ts file to configure the proxy, so I would only have to maintain my environment.ts instead of both files (also the proxy.conf.js).

Something along the lines of this:

import {env} from 'environments/environment';

const root = env.BASE_SUFFIX + '/*'; // BASE_SUFFIX = '/api'

function getConfig() {
  const PROXY_CONFIG = {};
  PROXY_CONFIG[root] = {
    target: env.API_URL, // API_URL = https://url.to.somewhere/
    logLevel: "debug",
    changeOrigin: true,
  };

  return PROXY_CONFIG;
}

module.exports = getConfig();

The problem I currently run into is that environment.ts is a Typescript file and cannot be correctly included by the javascript, because I have some import {foo} from 'bar' in my environment.ts file.

So const env = require(environments/environment.ts).env is not working, due to the ES6 imports.


Any suggestions on how I should do this or is this not possible and should I just use 2 separate files?



Solution 1:[1]

I'm using it this way. you can try this

// create proxy.conf.json

{
  "/api/*": {
    "target": "http://localhost:8000",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
  }
}

// in package.json file "scripts" under that find "start"

"start": "ng serve --proxy-config proxy.conf.json",

// api call

this.http.post('/api/api_name/')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Siddhartha Mukherjee