snowfrogdev
snowfrogdev

Reputation: 6853

Accessing dynamically generated server side environment variables in client side Angular app

I'm using the Heroku pipeline workflow which deploys review apps with dynamically generated URLs. For example, lets say my production app is deployed at mykickassapp.herokuapp.com, everytime I will make a PR in the repo, Heroku would automatically deploy that PR at something like mykickassapp-pr-50.herokuapp.com.

In my client side code, I make use of the environments files and store my apps URL in there, in the above example: mykickassapp.herokuapp.com. The problem is that it obviously doesn't work for the review apps deployed at a different dynamically generated URL. Thankfully, Heroku stores the app's URL in an environment variable. But the question is how to get it into the Angular app's client side?

My app uses the standard Angular-CLI production build process.

Upvotes: 2

Views: 967

Answers (1)

snowfrogdev
snowfrogdev

Reputation: 6853

I'm curious to see if anyone has a better or simpler way to do this but here is the solution I came up with.

I created a small js script that I saved in a config.js file in the root directory of the project. I then added that script in the npm postinstall script to run before ng build.

/src/environments/environment.prod.ts

export const environment = {
  production: true,
  URL: 'https://mykickassapp.herokuapp.com/'
};

config.js

const fs = require("fs");
const appName = process.env.HEROKU_APP_NAME;
if (appName) {
    const data = fs.readFileSync('./src/environments/environment.prod.ts', 'utf-8');
    const appURL = `URL: 'https://${appName}.herokuapp.com',`;
    const newValue = data.replace(/URL:(.*)/g, appURL);
    console.log(newValue);
    fs.writeFileSync('./src/environments/environment.prod.ts', newValue, 'utf-8');
}

package.json

...
"scripts": {    
    ...
    "test": "cross-env DEBUG=true jasmine",
    "postinstall": "node config.js && ng build --aot --prod"
  },
...

Upvotes: 5

Related Questions