Home > Enterprise >  How to avoid releaseing API public key in github for ReactJS application?
How to avoid releaseing API public key in github for ReactJS application?

Time:01-08

I was learning use of API in reactJS, When I made repository in GitHub and pushed my code there, My API_KEY was exposed there and i got mail from GitGuardian that my Secret is exposed,

Here's the code I have changed the key with API_KEY for this question,

export const geoApiOptions = {
  method: "GET",
  headers: {
    "X-RapidAPI-Key": API_KEY,
    "X-RapidAPI-Host": "wft-geo-db.p.rapidapi.com",
  },
};

export const GEO_API_URL = "https://wft-geo-db.p.rapidapi.com/v1/geo";

I was not aware that my API key would be exposed, So please let me know how should i avoid that in future.

CodePudding user response:

If you are simply using GitHub to document your code, you can store your API key in a separate file.

api-key.json

{
  "apiKey": "abcd1234"
}
app.js
import { apiKey } from "api-key.json";

export const geoApiOptions = {
  method: "GET",
  headers: {
    "X-RapidAPI-Key": apiKey,
    "X-RapidAPI-Host": "wft-geo-db.p.rapidapi.com",
  },
};

export const GEO_API_URL = "https://wft-geo-db.p.rapidapi.com/v1/geo";

And simply tell Git to ignore the file when publishing your code

.gitignore
# ...
api-key.json

CodePudding user response:

If you are using secret keys like API_KEY or DATABASE_URL and pushing source code to GitHub you should create a .env file in the root of your project. Then in your .env file, you can write your API_URL and use env variables in your source code. Then you should create a .gitignore file that ensures which files will be ignored when you publish your code to GitHub.

  • Related