'How to access environment variables with vanilla 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?



Solution 1:[1]

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

Solution 2:[2]

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:

  1. Go to the build settings
  2. 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
  3. 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
  4. 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>
  5. In your script file, import the variables by adding this line to the file: import {USERNAME, PASSWORD} from "./config.js"
  6. Trigger a redeploy manually on Netlify, or it will be deployed automatically if you already set automatic deploys for the repo.
  7. That's all!

This solved mine and I hope it helps anyone else?.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kevin
Solution 2 Airah