Home > Enterprise >  How can I use GitHub secret environment variables in a JS file?
How can I use GitHub secret environment variables in a JS file?

Time:09-01

I'm trying to use GitHub Secrets in a JS file that's used in a GitHub Pages website, which I'm trying to use to hide an API key, however, I have done a lot of research and I couldn't find or understand anything that could help me... Don't judge me, I'm a newby to GitHub! Anyways, here's the code I'm using:

document.getElementById("submit").addEventListener("click", function() {
    ...
    if (...) {
        var request = new XMLHttpRequest();
        request.open("GET", `https://script.google.com/macros/s/${process.env.API_KEY}/exec?...`, false);
        ...
    }
});

Is there a way this could be possible? Thanks!

CodePudding user response:

Github secrets are used in Workflow Actions. They aren't automatically injected into Github Pages.

You could write a workflow that, for example, reacts to commits to the main branch by running some code which generates new content in whatever branches you are using for Github Pages. The workflow you write to do that could pass the secret to the program generating the pages and it could inject the string into them.

However, the secret is then visible in the client side code published on Github Pages, so it largely renders the use of Github Secrets pointless.

CodePudding user response:

If you want to hide the info that you used in github-pages, it may help: 1)On the front-end React app as a sample: create a file named .env.local in your root and another file named .gitignore in root and write your secret code in .env.local it will automatically hide when you push code in your GitHub repo.

In .env.local:
REACT_APP_API_KEY = ANCCC.....
REACT_APP_AUTH_DOMAIN = my-app.firebaseapp.com
Using in another file:
apiKey:process.env.REACT_APP_API_KEY,
authDomain: process.env.REACT_APP_AUTH_DOMAIN,

Now if you push it will hide your firebase credentials automatically.

2)In node express Bankend as a sample: first:

Then create a file named .env and .gitignore in the root. In .env write secret credential:

in .env file:
DB_USER=dbuser
DB_PASS=39T6.......

in index.js file/where you want to use:

require('dotenv').config();

and instead of password and DBname:

${process.env.DB_USER}:${process.env.DB_PASS}

Now finally in .gitignore write the file name as below:

.env
node_modules

Push the code in GitHub. Hope it works.Thanks.

  • Related