Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access environment variables on Heroku from AngularJS

I have 3 of AngularJS apps on Heroku. Each of them consumes different API.

(For example: angularjs-dev consume api-dev, angularjs-qa consumes api-qa)

I created constant file like this below

SITE     = 'dev'
API_SITE = {
      dev       : 'dev-url',
      qa        : 'qa-url',
      production: 'production-url'
}

And then when I want the API url, I call it this way API_SITE[SITE]

This problem is when I want to deploy to qa, I have to change SITE to qa.

I wonder that: can we make AngularJS read environment variables defined on Heroku so we won't have to change it manually again

Note: I know that AngularJS is running on client-side. So, I have no idea how to do it.

Anyone?

like image 204
Bun Suwanparsert Avatar asked Nov 13 '14 07:11

Bun Suwanparsert


People also ask

How do I change my environment variables in Heroku?

One way of setting the environment variables on Heroku is to use the web interface. The first step is to log into your account and go to the Heroku dashboard. Figure 1 illustrates my dashboard. Choose the application for which you want to set the environment variables.

Does Heroku use .ENV file?

Heroku Local is a command-line tool to run Procfile-backed apps. It is installed automatically as part of the Heroku CLI. Heroku Local reads configuration variables from a . env file.

What are config vars in Heroku?

Config Vars Anything that you don't want to appear in your source code (like API keys or database login credentials), as well as anything that varies between environments (like usernames, or URL's) should be stored in environment variables. Heroku's environment variables are called config vars.

Are Heroku config vars safe?

Heroku config vars are designed to be safe for storing sensitive information. All config vars are stored in an encrypted form and safely stored. These are only decrypted and loaded when booting your app in a dyno itself. Save this answer.


1 Answers

In case that someone is looking for the solution (based on my environment: AngularJS and NodeJS on Heroku)

I added this code to web.js (NodeJS starter file)

var options = {};
var jade = require('jade');

app.get('/site.js', function(req, res){
    res.send("var SITE='"+process.env.SITE+"'");
});

Then, in file index.html I just added <script src="/site.js"></script> for retriving SITE variable.

It works well.

like image 191
Bun Suwanparsert Avatar answered Sep 19 '22 05:09

Bun Suwanparsert