Motivation
React's Context management is great for keeping a Firebase Singleton for your application. By also setting up a Context specifically for Sessions, you can make sure that certain components are only accessible via successful authentication.
If you are initialising firebase like this
1
import firebase from "firebase/app";
2
import "firebase/firestore";
3
import "firebase/auth";
4
import "firebase/storage";
5
import "firebase/functions";
6
​
7
const firebaseConfig = {
8
apiKey: process.env.REACT_APP_API_KEY,
9
authDomain: process.env.REACT_APP_AUTH_DOMAIN,
10
databaseURL: process.env.REACT_APP_DATABASE_URL,
11
projectId: process.env.REACT_APP_PROJECT_ID,
12
storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
13
messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
14
appId: process.env.REACT_APP_APP_ID,
15
measurementId: process.env.REACT_APP_MEASUREMENT_ID
16
};
17
​
18
// Initialize Firebase
19
firebase.initializeApp(firebaseConfig);
20
​
21
export const db = firebase.firestore();
22
export const functions = firebase.functions();
23
​
24
firebase.functions().useFunctionsEmulator('http://localhost:4001')
25
export default firebase;
26
​
Copied!
Using these Create React App Env in a .env (added to .gitignore)
1
# Firebase
2
REACT_APP_API_KEY=""
3
REACT_APP_AUTH_DOMAIN=""
4
REACT_APP_DATABASE_URL=""
5
REACT_APP_PROJECT_ID=""
6
REACT_APP_STORAGE_BUCKET=""
7
REACT_APP_MESSAGING_SENDER_ID=""
Copied!
Or
1
REACT_APP_API_KEY=""
2
REACT_APP_AUTH_DOMAIN=""
3
REACT_APP_DATABASE_URL=""
4
REACT_APP_PROJECT_ID=""
5
REACT_APP_STORAGE_BUCKET=""
6
REACT_APP_MESSAGING_SENDER_ID=""
7
REACT_APP_APP_ID=""
8
REACT_APP_MEASUREMENT_ID=""
Copied!
and importing it in your React app side code
1
...
2
import firebase, { db } from "../../Firebase.js";
3
...
Copied!
you might be getting this warning message in the console.
@firebase/app: Warning: Firebase is already defined in the global scope. Please make sure Firebase library is only loaded once.
There's a better implementation as shown in the next section, using React context and higher order components.
Copy link