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!
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
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
Related
I'm developing a full-stack web app, which has both a frontend and a backend. In production, my frontend will be hosted at https://frontend.com, and my backend at https://backend.com. It seems reasonable to hardcode the address https://backend.com in my frontend code.
However, when I am testing the app locally, I'll want to spin up the backend at, say, localhost:8000, and redirect my frontend to this address instead. My question is: what's the easiest/most elegant way to do this?
One approach is to manually change the frontend code to point to localhost:8000 for local testing, and then change it back before deploying. However, this is quite annoying, and it's too easy to forget to change it back.
An approach I've used in the past is:
Create a file server.js containing:
const LOCAL_SERVER = "http://localhost:8000"
Import this file in my frontend HTML:
<script src="server.js"></script>
Set a fallback to the remote/production server in my JS scripts:
let SERVER = typeof LOCAL_SERVER === 'undefined' ? 'https://backend.com' : LOCAL_SERVER
Add server.js to my .gitignore.
This works, but it feels kind of hacky, and it pollutes my production code with references to this (possibly non-existent) server.js and LOCAL_SERVER constant. I'm wondering if anyone has a better way.
If your real backend & local backend use the same port, a simple solution is to add the following line to your hosts file:
127.0.0.1 backend.com
This may be a dumb question, but how to get access to process.env vars inside of my ember app? I tried to access process.env in one of my controllers, but I received an error that process was not defined.
You generally don't have access to process.env since this is node.js global variable and ember.js generally runs in the browser which will not have process.env
However, you can use process.env during the build process which will produce ember app with the env variables build-in which you can access in another way.
I'm not sure what tooling you are using but here is how it works in Ember CLI Deploy:
http://ember-cli-deploy.com/docs/v1.0.x/using-env-for-secrets/
And here is an example with webpack:
https://webpack.js.org/guides/environment-variables/
I would like to use environment variables to securely hold secrets with pm2.
I have a reverse proxy to an express backed server that uses a database with a password each time it connects to preform a query.
I would like to access it normally from the program:
procsess.env.my_secret
but I'm assuming that simply setting the variable at run time like the following isn't safe:
MY_SECRET="secret password" pm2/node my_api_server.js
How should I set the secret password considering I'm using pm2 and I would like the variable to persist through restarts/crashes?
I should note that different environment handling and passing code to other developers through the VCN is less important to me.
Storing API keys or credentials using .env gets exposed to the client on Production!
By React docs -
WARNING: Do not store any secrets (such as private API keys) in your React app!
Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.
It's advised to store all env keys directly on the server and the server should be used as a mid point between the client and the API. This way the key is applied directly on the server and is not exposed in the front end. You can check out respective documentation on how to set up env variables on your particular server.
Front End Code
fetchData = () => {
fetch('/users', { method: 'POST', body: JSON.stringify(data) }
.then(res => res.json())
}
Server Code
app.post('/users', (req, res) => {
const API_KEY = process.env.API_KEY;
connection.query(`/apiPath/${API_KEY}`)
}
In past ReactJS projects with Express backends that need to connect to a database, I've used the dotenv package on NPM. Once added as a dependency to your project, you will create a hidden .env file in the root of your server filestructure.
In that .env file, you can create environment variables. These variables will need to be prefixed with REACT_APP like the following:
REACT_APP_DBURI=<conn string here>
REACT_APP_MAILGUN_API_KEY=<key string here>
REACT_APP_CAPTCHA_SECRET_KEY=<key string here>
You need to require the package as follows in your code:
require('dotenv').config();
You can reference them in your server.js (or whatever) code as:
process.env.REACT_APP_VARIABLE_NAME
This Medium article has a full explanation.
Hope this helps!
Is there a way to force Node-webkit to use proxied settings for all requests ? I know there is an API solution using setProxyConfig() but this doesn't work with authenticated proxy, the prompt shows up to login but crash when submitted...
So I tried to use node request module, and it works fine :
var request=require('request');
var proxy = request.defaults({'proxy':'http://login:pwd#proxy:port'});
But now my problem is to tell node-webkit to use this for each request.
Any solutions ?
I'm quite new using node and node-webkit so maybe there is a better way to do that.
Thanks a lot !
You may try
process.env.http_proxy = 'http://login:pwd#proxy:port'
It will work with request lib, also should impact other requests from node-webkit (assets, ajax)
But may be other libraries don't use environment proxy settings. If that doesn't work you can try https://www.npmjs.com/package/global-tunnel
Not sure if this is solved, but i came up with a simple solution:
i wrote a simple wrapper for the request library
https://gist.github.com/jodevsa/7dd9662b8244359fa0d7626ae7c9bd69
all you have to do is ,
Head to $PROJECT_DIR/node_modules/request/
Rename index.js to core.js
Create a new file called index.js
Copy code content from the above gist link to index.js
Change proxyLoc value to you'r preferred proxy
If you decided to disable proxy , just change value of ON variable to false inside index.js
Cheers :D
I have frontend content that needs backend REST APIs to function. The APIs allow for cross-origin resource sharing (CORS). Typically we run the complete stack locally, including a user-mode Nginx instance tailored for development use which serves the frontend content. The full stack however is a bit too much to expect part time contractors to wrangle. So I'd like an approach very basic they can use to be effective and get stuff done.
Their current solution is horrible:
var port = location.port;
// base url of backend API
var url = window.location['origin'];
if (port != '443') {
// assume we're running in "development" mode against a staging server
url = "https://staging-server.somewhere.com";
}
Apart from the fact that this is furthering frontend content that is a bit kludgey as it is - it precludes the static content from being hosted in a variety of other ways, including a suite of functional and integration tests.
I have some ideas, like having them run a small web server that proxies to the backend APIs, but what I would really like is something simpler that allows me to default url in a less kludgey way. Ideally, there would be some manner of configuring url from a file ignored by version control (e.g., .gitignore).
I was able to create a solution that works for all manner of local development as well as production releases.
I created some JavaScript, apiurl.js, that sits alongside all of our other JavaScript content. If the apiurl.jsfile is present, I read its responseText into eval(). The frontend can therefore change the URL based on the content of that file.
E.g., apiurl.js has:
var apiurl = "https://staging-server.somewhere.com";
And the JavaScript to handle the content:
eval(responseText);
if (typeof(apiurl) != undefined) {
url = apiurl;
}
The apiurl.js file is untracked by version control and not used in production.