hide api key for a Github page

In short yes, you can store the auth token in an environment variable and use gitignore on the .env file to hide the auth token in the public repo. Refresh the auth token on the client-side API then push changes to the public repo and redeploy your updates to the gh-pages branch. I've provided an example of this process below.

NOTE

If you committed a password or API key, change it! If you committed a key, generate a new one. Reference general best practices on GitHub.

If using React for your app, SKIP steps 1 and 2 as React already comes pre installed with custom environment variables. Reference Create React App.

The full explanation can be found below:

1. Install dotenv dependency in application root directory (will be using Node.js for this example) Reference npm, run command:

npm install dotenv

2. Add code below to import statements in index.js file.

require('dotenv').config();

3. Create .env file in root directory of app and add auth token as variable. Note when using React you must prepend variable name with REACT_APP_

AUTH_TOKEN=987asc8iks0lenv7

4. Use console.log() on process.env to check if the variable was stored correctly.

console.log(process.env.AUTH_TOKEN);

5. Update all references to auth token in application code.

OLD VARIABLE: const auth_token = '987asc8iks0lenv7';

NEW VARIABLE: const auth_token = process.env.AUTH_TOKEN;

6. Create and add .gitignore file to the root directory of application and add code below to have git ignore the .env file where the auth token is stored.

.env

7. Add, commit and push updates to application master branch on GitHub.

8. To deploy or redeploy updates to gh-pages branch. Use command below.

npm run deploy


In short, no. If your GitHub repo is public, all its assets are public. You can make the repo private and it will still publish on GitHub Pages if named with the username.github.io convention or if it has a gh-pages branch. While that's an option, that's not necessarily the right thing to do.

If your key is in your GitHub Pages repo, it sounds like it's used for client-side API calls in JavaScript. If so, your auth token is publicly visible whether it's in your public repo or sent in your client-side files to the browser. This is usually fine. The third-party API might have generated the auth token based on your website's domain, and restrict calls using that token to pages originating on your domain. Otherwise, they might require the auth token only for logging requests and monitoring usage.

If the auth token is truly meant to be private, then you may need to write private server-side code to call the third-party API. Your GitHub Pages site could then hit your service for the data it needs. I've had to do that before where the web API had security concerns, but I still needed to retrieve non-sensitive data from the client-side.