Recently I was trying to work on a web project to track each user's progress on Freecodecamp platform to get / fetch their point using React Vite and Firebase just to practice ReactJs and integrate firebase to add more functionality.
My goal was to secure the Api Key by preventing it from pushing it to Github. I researched on getting this done and i decided to document it because this can help others who will be looking for a way to achieve same goal using Vite since the way to achieve this with Vite different from using create-react-app.
These are the following steps to achieve the goal.
- Just create a .env file at the root of the folder/ project and add all your API key as below example. Ensure you start with the VITE word.( E.g, VITE_SOME_KEY=123). (step 1)
VITE_FIREBASE_API_KEY=AIzaSyAlL9BFqrGofCzlcJQOdSATQWSCpU8RybM
VITE_FIREBASE_AUTH_DOMAIN=advanced-login-signup.firebaseapp.com
VITE_FIREBASE_PROJECT_ID=advanced-login-signup
VITE_FIREBASE_STORAGE_BUCKET=advanced-login-signup.appspot.com
VITE_FIREBASE_MESSAGING_SENDER_ID=71315803652
VITE_FIREBASE_APP_ID=1:71315803652:web:db96ed49092ea0824daf51
Make sure you add .env file in .gitignore to prevent it from pushing on to the GitHub.(step 2)
To use the key just use it like below code snippet. This is my firebase.js file.(step 3)
import {getAuth} from "firebase/auth"
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN,
projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET,
messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID,
appId: import.meta.env.VITE_API_ID
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app)
export default app
Now understand that to use the variable names from .env file in our firebase.js file we make use of import.meta.env.VITE_SOME_KEY.
Congratulation we just secure our Api Key from exposing and pushing it to Github.
Top comments (2)
Hi, welcome to the community,
Thanks for sharing your experience. It is very informative and could help begginers protect the sensitive data from being pushed to the version control. Hope to see more of your experience helping the community
Thanks for this positive response, it really mean a lots to me in doing more.
Best Regards