How to access environment variables with vanilla javascript - javascript

I have an index.html and I need to pass some sensitive information to some JavaScript variables. This index.html contains plain javascript with jquery
so I am settning environmental variable like this:
USERNAME="123"
PASSWORD="password"
And I need to access this using javascript
<script>
var username = process.env.USERNAME;
var pw = process.env.PASSWORD;
</script>
but this gives the error
Uncaught ReferenceError: process is not defined
Maybe this is because I am using vanilla javascript. And I can't use any other framework other than jquery
Can someone help me how to do this?

I had this exact issue to deal with and I was able to create a working solution using this article. For this answer, I'll summarise the steps I took for a project deployed to Netlify and already modified to fit your question, but you can check out the article to see the base example and also learn more.
Note: This solution is ideal for small personal projects where the information is not exactly sensitive but you just don't want them
displayed so visibly in your code. Do not use for larger projects that require a reasonable level of security measures.
If your project is already deployed to Netlify, or a similar platform where you can add build/deploy commands:
Go to the build settings
If the script file you want to use the variables for is in a folder, set the build command to this: cd DIRECTORY-FOR-THE-SCRIPT-FILE && echo -e "export const USERNAME="123";\nexport const PASSWORD="password";" > config.js
If the script is in your root folder, set the command to this echo -e "export const USERNAME="123";\nexport const PASSWORD="password"; > config.js
In your index.html file where you import the script, set your script tag to include this attribute type="module" i.e <script src="./index.js" type="module"></script>
In your script file, import the variables by adding this line to the file: import {USERNAME, PASSWORD} from "./config.js"
Trigger a redeploy manually on Netlify, or it will be deployed automatically if you already set automatic deploys for the repo.
That's all!
This solved mine and I hope it helps anyone else✨.

So what is your environment? javascript runs in the frontend, where are you setting the env variable?
You may be able to use something like fs - https://www.npmjs.com/package/file-system to read from a file on the operating system, but I would not imagine most browsers would allow this

Related

Firebase functions in multiple separate folders

My source code looks like this:
API/index.ts (includes 1 firebase function trigger)
Extra/index.ts which includes
exports.ml_files = require("./ai-func");
exports.authHandler = require("./user-function");
exports.fileUploadListen = require("./fileupload.listener");
// exports.graphql = require("../API/src/index");
Currently my functions source directory directory is Extra. How do I make sure that the functions defined in API also get included in the final build? If I try to use exports.graphql the build breaks.
You must move all source code into the "functions" folder for deployment. The CLI will only deploy content from that folder, and from nowhere else. It's not possible to configure it otherwise - you must have a single folder where everything lives. As such, paths given to require() that look outside the folder (as you are doing now with ..) will simply not work.
I would recommend to try this concept of separation explained here.
We use it every of our Firebase projects and we are very happy with it :)

How to use Node.js packages within a client-side html document using browserify

I'm unable to use a node.js module on my website with broweserify. The example only shows how to run a javascript file that is separate from the .html file, not how to use the node.js module within the .html file. Seems like a trivial problem, but I'm unable to make it work.
Here's what I've done:
Initialized node.js & installed a package, npm i webtorrent-health as an example
Created require_stuff.js which consists of a single line: var WebtorrentHealth = require('webtorrent-health')
Run browserify: browserify require_stuff.js > bundle.js
Include package in my html document, e.g. <script src='bundle.js'></script>
Use the package somewhere in my document, e.g. like this: <script>webtorrentHealth(magnet).then(foobazbar())</script>
Despite bundle.js executing and seemingly defining webtorrentHealth, the script within the .html document fails with WebtorrentHealth is not defined. What am I doing wrong? How do I make it work? Thank you!
You're very close to what you want to achieve. In fact, your code bundle.js is inaccessible from outside (in your case the browser) due to browserify, but you can expose your module by writing at the end of your file require_stuff.js:
window.WebtorrentHealth = WebtorrentHealth;
Now you can use WebtorrentHealth in your document.

Require is not working for node-opcua

I want to load a local version of node-opcua with 'require' inside a HTML file, but it does not really work. The code snippet is the following:
<script type="text/javascript" src="path_to_require.js"></script>
<script>
var opcua = require(["path_to_node-opcua"]); <!-- Yes, the path is correct >
var client = new opcua.OPCUAClient();
...
When I execute the script I get the following error in the console:
Uncaught TypeError: opcua.OPCUAClient is not a constructor
Hence, var opcua is loaded correctly, but OPCUACluent is not, although the class is declared in a file that is present in the node-opcua folder called opcua_client.js under node-opcua\lib\client\
Sources:
The 'require' script from http://requirejs.org/docs/download.html#requirejs.
The node-opcua folder with the console command
npm install node-opcua.
node-opcua is not intended to run inside a browser as it relies on nodejs specific features such as filesystem access, crypto and so on.
You need to use browserify if you want to use that module in client. You will also need to look at how to use browserify with file system access (it can be done if paths are known ahead of time).

What is the proper way to set up a jsbindings class with cocos2d-js?

The documentation explains how to generates jsbindings, but it does not tell the proper way to integrate it into a project. What steps do I must follow? Where should I store my manually written C++ files? Where should I store the generated js and c++ files? What CMakeList.txt files should I edit?
I believe I found some way to do this.
Please confirm me I don't do anything wrong (I copied this message on the official forum).
Let's integrate the js-bindings test samples in a cocos2d-js project.
First generate the tests : cd tools/bindings-generator/test && ./test.sh && cd ../../.. (that may need some configuration). At the moment it fails on Linux because of missing headers but I submited a merge request.
Copy files into the project
cp -R tools/bindings-generator/test/simple_test/ frameworks/runtime-src/Classes
cp -R tools/bindings-generator/test/simple_test_bindings/ frameworks/runtime-src/Classes
Update CMakeLists.txt and frameworks/runtime-src/proj.android/jni/Android.mk and add the added files autogentestbindings.cpp and simple_class.cpp to the target lists.
Register the jsb functions in the runtime sources in frameworks/runtime-src/Classes/AppDelegate.cpp by adding sc->addRegisterCallback(register_all_autogentestbindings); in AppDelegate::applicationDidFinishLaunching
Then classes defined in simple_class.h are available in Javascript. The following JS code should display 1337.
console.log((new SimpleNativeClass(1337)).getSomeField())

Basic requirejs concept needed to make work musicjson package

I'd like to use the musicjson.js package that helps to convert musicXML files into json notation, looking if it's a good way to import for example exported musicXML Finale scores into a browser playing with the Fermata/VexFlow class.
https://github.com/saebekassebil/musicjson
The thing is that this module works with require (calling for
nodes packages like fs) and I'm just a newbee in requirejs...Even if I spent few time in understanding the tutorial in the website, I don't still get how to solve this kind of basic problem when the dependencies of my musicjson.js need to be called like :
var xmldom = require('flat-xmldom'),
fs = require('fs'),
path = require('path'),
util = require('util');
My index.php page does the classic require call:
<!DOCTYPE html>
<head>
<!-- javascript head -->
<!-- REQUIRE -->
<script data-main="scripts/main" src="bower_components/requirejs/require.js"></script>
</head>
<body>
</body>
</html>
In my scripts/main.js, I'd like to do simply what it is told from musicjon :
var music = require('musicjson');
music.musicJSON(xml, function(err, json) {
// Do something with the MusicJSON data
});
I putted also, in the same directory scripts/, the flat-xmldom folder, fs.js, path.js, util.js
When I do this, I've just obtain this classic error of :
*Error: Module name "musicjson" has not been loaded yet for context: _. Use require([])*
...That looks like a common error referenced in the requirejs website,
but if I try things that I guess it should be written, I get a bit lost to determine where is the fundamental conceptual mistake here :
require.config({
baseUrl: '/scripts/',
paths: {
flatxmldom:'./flat-xmldom/__package__',
fs: 'fs',
path:'path',
util:'util',
musicjson: 'musicjson'
}
});
require(['flatxmldom','fs','path','util','musicjson'],function(flatxmldom,fs,path,util,musicjson){})
Error returned in this case for example :
*Module name "fs" has not been loaded yet for context: _. Use require([])*
Thanks a lot for your attention.
So, this is not a RequireJS problem per-se. The package you want to use is a Node.js package. It is intended to run in node (a server/desktop execution environment for JavaScript). It cannot/will not run in web page in a browser.
The packages it is trying to use (fs in particular) provide access to system resources such as the file system. Node provides these packages as part of its core libraries to any package that runs in node. A browser is specifically designed for security reasons never to allow direct access to such resources to any code that run in the browser because who knows where it came from or might try to do.
I haven't really tried to do this myself, but browserify (alternative to requirejs) claims that it will allow you to use any node package in your application.
If musicjson is at the heart of what your app should achieve and requirejs is a small step on the way to getting there, you could try your luck with browserify instead.

Categories

Resources