Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access local ENV variables in angular js

Is it possible to access ENV variables from angularjs?

I've got an angular 1.2.8 app being compiled via Brunch.io

It's hosted as a basic node app on heroku. (I do compiling locally; then push)

I've read a few things about token replacement during the compile stage for ENV variables.

However I'd much rather be able to push up the code to several different servers and have it resolve the correct local settings using just the ENV variables.

Thanks!

like image 511
David Harkness Avatar asked Jan 14 '14 14:01

David Harkness


People also ask

Can Angular access environment variables?

If you're building an app that uses an API, you'll want to use your API key for testing environments during development and your API key for live environments during production. In Angular, you can create environment variables with the environment.

How do I find local environment variables?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables.

Can I use dotenv in Angular?

While developing an Angular app with Angular CLI, it's not very easy to integrate the dotenv package. After a few hours of research, I found a process that works well enough. Most Node developers use dotenv as a way to manage private API keys.


2 Answers

There are multiple ways of doing it and as mentioned above you could simply make and API call, however that creates an unnecessary delay in your app. I would recommend to inject your env variables into your angular constant service on your server. That probably sounds a bit confusing, but it's simpler than it sounds.

I have written a blog post comparing different ways of injecting env varialbes into angular and explaining why you should take this approach: https://medium.com/@kudresov/a-better-way-to-inject-environmental-variables-in-angular-d3b2d01a3c5e

Also I have created sample Node Angular project to show how it works: https://github.com/kudresov/angular-config-vars

like image 43
Vitalij Avatar answered Nov 15 '22 06:11

Vitalij


You cannot get ENV variables on browser. You can send request to a rest service on your server, and get env on backend, then response back to client

Quick example: (Express.js)

app.get("/rest/getenv", function(req, res) {
    var env = process.env.ENV_VARIABLE;
    res.json({result: env});
});

Edit:

You need to protect this rest url with token like strings. Or else, anyone can reach that url and get your environment variable value. This can be security concern

like image 164
Hüseyin BABAL Avatar answered Nov 15 '22 06:11

Hüseyin BABAL