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:
build settingsbuild command to this: cd DIRECTORY-FOR-THE-SCRIPT-FILE && echo -e "export const USERNAME="123";\nexport const PASSWORD="password";" > config.jsecho -e "export const USERNAME="123";\nexport const PASSWORD="password"; > config.jsindex.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>import {USERNAME, PASSWORD} from "./config.js"This solved mine and I hope it helps anyone else✨.
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