React
How to hide Firebase API Keys in React and Next.js
Hiding your environment API Keys can be challenging, especially if you are a beginner like me. In this post I will provide examples to do it, so your API keys don’t get exposed on your GitHub repository if you set it up as public.
Create React App
Step 1 – Create a folder called `.env`.
Step 2 – Make sure you add the `.env` to your `gitignore` file so you don’t push this file to your GitHub repository.
Step 3 – Type the code below and add your key values:
REACT_APP_API_KEY = ‘key values’ REACT_APP_AUTH_DOMAIN = ‘key values’ REACT_APP_PROJECT_ID = ‘key values’ REACT_APP_STORAGE_BUCKET = ‘key values’ REACT_APP_MESSAGING_SENDER_ID = ‘key values’ REACT_APP_APP_ID = ‘key values’
Step 4 – Add the key variables to your firebase config file.
// Initialize Firebase const firebaseConfig = { apiKey: `${process.env.REACT_APP_API_KEY}`, authDomain: `${process.env.REACT_APP_AUTH_DOMAIN}`, projectId: `${process.env.REACT_APP_PROJECT_ID}`, storageBucket: `${process.env.STORAGE_BUCKET}`, messagingSenderId: `${process.env.MESSAGING_SENDER_ID}`, appId: `${process.env.REACT_APP_APP_ID}`, };
Now your application should be working the same way it was before.
Next.js
Step 1 – Create a folder called `.env`.
Step 2 – Make sure you add the `.env` to your `gitignore` file so you don’t push this file to your GitHub repository.
Step 3 – Type the code below and add your key values:
NEXT_PUBLIC_FIREBASE_API_KEY = ‘key values’ NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN = ‘key values’ NEXT_PUBLIC_FIREBASE_PROJECT_ID = ‘key values’ NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET = ‘key values’ NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID = ‘key values’ NEXT_PUBLIC_FIREBASE_APP_ID = ‘key values’
Step 4 – Add the key variables to your firebase config file.
// Initialize Firebase const firebaseConfig = { apiKey: `${process.env.NEXT_PUBLIC_FIREBASE_API_KEY}`, authDomain: `${process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN}`, projectId: `${process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID}`, storageBucket: `${process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET}`, messagingSenderId: `${process.env.MESSAGING_SENDER_ID}`, appId: `${process.env.NEXT_PUBLIC_FIREBASE_APP_ID}`, };
Now you application should be working the same way it was before.
Deployment:
Before deploying your website you will need to add your environment variables since they won’t be able to read your `.env` file.
Devzilian