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!
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With