I have a number of JavaScript projects that require an API key or other secret information that I don't wish to share with the outside world. This is a problem if I share the rest of the source code in a public GitHub repository.

Here is how I handle it.

  1. Create a getkey.js file with a single getKey function.
  2. Include getkey.js in my HTML document(s).
  3. Call getKey() from another JavaScript file, but wrap the call in a try/catch block. If an error occurs, warn the user that they must add this file / function.
  4. Add a .gitignore file to my project to exclude getkey.js
  5. Check the rest of the project into GitHub.

Create a getkey.js file

Here are the contents of my getkey.js file:

var getKey = function(){
    return "3899084ab2353243735944a95b0eba51";
}

Of course, the return value will be your appropriate key.

Include getkey.js in my HTML document(s)

JavaScript is called from script files referenced in my HTML documents. I typically have a file named "script.js", which contains the main functions for my page. So I include both that file and getkey.js within the tag as shown below.

<script src="scripts/script.js"></script>
<script src="scripts/getkey.js"></script>

Call getKey() from another JavaScript file

From script.js, I add code to call the getKey() function within a try/catch block. This will throw an exception if the script cannot find the getKey function (usually because it cannot find the getkey.js file). In this example, I output a useful error message in a DIV with an ID of "OutputDiv".

Here is the relevant code.

const missingKeyErrorMsg = `<div>No key found.<br>
	This demo will not work without a key.<br>
	Create a script.js file with the following code:.</div>
	<div style="color:red; padding-left: 20px;">
	var getKey = function(){<br>
		&nbsp; &nbsp; return "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";<br>
	}
	</div>
	<div>where xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx is your Azure Face API key</div>`

try {
	var subscriptionKey = getKey();
}
catch(err) {
	$("#OutputDiv).html(missingKeyErrorMsg);
	return;
}

Add a .gitignore file to my project to exclude getkey.js

I want to keep the getkey.js file locally, but I don't want to check it into GitHub. Adding a file named ".gitignore" in the root of my project allows me to list any files or folders that I don't want to include in my GitHub repository.

Add the following line to the .gitignore file

getkey.js

Check the rest of the project into GitHub.

Once the above steps are completed, it is safe to check it into GitHub. The getkey.js file will not be checked in. When another user checks it out, they will need to create this file. I recommend creating a read.me file and pointing this out.

Even if they forget, the error message should give them an idea why their code is not working.

There are other ways to address this issue, but this way works for me.