Hide API key in Javascript


Below 6 steps are for hiding the API key in Vanilla JavaScript code. No framework is used here.
If you wan’t to hide your API key from the browser, follow the below steps to successfully hide it from being used by anyone else.
Step 1 : Create a new javascript file named apikey.js
Step 2 : Add the API key in apikey.js
file
// File name = apikey.js
API_KEYS = "eeeeeeeeexampleapikeyaaaaaaaaaaa";
Step 3 : Update index.html
file, two separate JS file created.
<script type="module" src="index.js"></script>
<script src="apikey.js"></script>
Step 4 : Update index.js
file, store API_KEYS in constant variable apiKey
// File name = index.js
const apiKey = API_KEYS;
Finally, use this apikey variable to fetch the apiURL.
Step 5 : Add file apikey.js
to .gitignore
If gitignore file is not present, create it!
// File name = .gitignore
apikey.js
Step 6 : Restart the port, console now should not show any error related to fetching the API
Subscribe to my newsletter
Read articles from Preetika Prakash directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Preetika Prakash
Preetika Prakash
Attempting #100DaysofCode challenge | Open Source Contributor