I have a vanilla js project. In app.js file I am calling a api that retrieves the desired values. I have initially called the api through postman, included all the headers in postman only and retrieved the code using javascript fetch. It works good too but it shows my token and session id in it.
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Authorization", "Token <mytoken>");
myHeaders.append("Cookie", "sessionid= <mysessionid>");
myHeaders.append("User-Agent", "Mozilla/5.0");
How can i hide these values in .env file.
Thank you
Do it by writing this in terminal:
npm install dotenv
Do it by writing this in terminal:
npm install requirejs
var requirejs = require('requirejs');
requirejs.config({
//Pass the top-level main.js/index.js require
//function to requirejs so that node modules
//are loaded relative to the top-level JS file.
nodeRequire: require
});
requirejs(['foo', 'bar'],
function (foo, bar) {
//foo and bar are loaded according to requirejs
//config, but if not found, then node's require
//is used to load the module.
});
Read more about this at https://www.freecodecamp.org/news/how-to-use-environment-variables-in-vanillajs/
There is a good way to solve this without installing packages.
I wrote an answer here but I might as well share here too.
I was able to create a working solution using this article. You should modify the steps below with your own variables, and you can also 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✨.