To create or setup a new React app, I try to use npx
from a terminal window. By executing the following command, it generates a new React app using the create-react-app
utility.
npx create-react-app reactapp
# after the project has generated
cd reactapp
The name of the project reactapp
mentioned in the command is the project name. To start this newly created React app, run the below command from the terminal window:
yarn start
It will trigger the default React app that is generated by create-react-app
command-line utility and open the app in a browser window at URL http://localhost:3000
.
Now, setup the project as per the need. The following directory basic setup is how I like to setup a new React app (when using Firebase as the backend service).
Add an initial modification of src/App.js
file to the file code snippet.
import React from "react";
function App() {
return (
<div>
<h1>React App</h1>
</div>
);
}
export default App;
This modification is going to lead to the following change in a web browser window.
Create Firebase project-based components
The basic directory structure is all setup, now let’s create the Firebase project-related component folders. Each component folder inside src/components/
is going to have an index.js
file that is going to contain the code snippet related to that particular component.
For example, in a Firebase + React app, the sign in, sign out and sign up component is going to be three different components to handle user authentication. Thus, all are going to have separate folders. To create a component folder you can use the command-line interface or the editor or the IDE file explorer.
cd components/
mkdir SignIn SignOut SignUp
The ./src/Pages
directory is optional. I like to separate presentation page components such as Home
or Landing
in a different folder but that depends on the project itself.
The initial components directory is done. In the next section, let us get the API keys from the Firebase project.
Generate Firebase API keys
Before you generate API keys for Firebase configuration in a React app, please make sure you have either set up a new Firebase app or have access to a Firebase app using its console.
If you are new to Firebase apps, please refer to the post here that explains 👉 how to create a new Firebase project?
Once you have created or opened a Firebase project, from the dashboard screen, click on the settings icon ⚙️ from the side menu.
The Settings page opens as shown below.
To create a new app, go to the section that says Your apps
and click on the third icon or the Web icon. The first two icons shown are for creating keys for native platforms such as iOS and Android.
Next, there is going to be a prompt about adding the name of the web app. Enter a name.
Then the API keys required by the web app are generated as shown below. The blacked-out part is the actual key values and I recommend not sharing with anyone.
Make sure you save the firebaseConfig
object. It is the object the contains all the API keys required to use various Firebase services such as authentication, database and so on.
Once you copied the firebaseConfig
object, you press the button that says Continue to console
. You are going to be taken back to the Settings
page.
Environment variables in a React app
Create a new file inside the React project called .env
. Make sure to add this file to .gitignore
and do not commit it to the GitHub repo or any other public repository on a version control platform.
This file is going to save all the Firebase API keys as shown below. All the xxxx
’s represent the keys generated in the Firebase console. Replace them with your own keys.
DEV_API_KEY=xxxx
DEV_AUTH_DOMAIN=xxxx
DEV_DATABASE_URL=xxxx
DEV_PROJECT_ID=xxxx
DEV_STORAGE_BUCKET=xxxx
DEV_MESSAGING_SENDER_ID=xxxx
DEV_APP_ID=xxxx
DEV_MEASUREMENT_ID=xxxx
You do not have to name each key with the prefix `DEV_`. You can either use their default name such as `API_KEY` or follow your own convention. I like to follow `DEV_` and `PROD_` prefixes to separate dev mode and production mode Firebase projects.
Connect Firebase with a React app
React app needs Firebase SDK installed as an npm dependency. Open terminal window, execute the following command to install the dependency.
yarn add firebase
For Firebase SDK to initialize with the React app and use the Firebase services further in the app, it needs to consume the API keys generated in the previous section as a configuration object. This object is a plain JavaScript object with key and value pairs.
Create a new file src/Firebase/firebase.js
import the firebase
library and create a firebaseConfig
object with appropriate keys and their values saved in .env
file.
// firebase.js
import * as firebase from "firebase/app";
const firebaseConfig = {
apiKey: process.env.DEV_API_KEY,
authDomain: process.env.DEV_AUTH_DOMAIN,
databaseURL: process.env.DEV_DATABASE_URL,
projectId: process.env.DEV_PROJECT_ID,
storageBucket: process.env.DEV_STORAGE_BUCKET,
messagingSenderId: process.env.DEV_MESSAGING_SENDER_ID,
appId: process.env.DEV_APP_ID,
measurementId: process.env.DEV_MEASUREMENT_ID,
};
The firebase/app
import statement is always required when you add the Firebase SDK to a new Web app or React project. It should also be the import statement line in this file.
The current format of firebaseConfig
object shows that all the Firebase services from its console are enabled.
Side-note: To use a different set of API keys or Firebase projects such as for development and production, you can create two `config` objects here. For dev mode, create `devConfig` and for production, create `prodConfig`.
const prodConfig = {
apiKey: process.env.PROD_API_KEY,
authDomain: process.env.PROD_AUTH_DOMAIN,
databaseURL: process.env.PROD_DATABASE_URL,
projectId: process.env.PROD_PROJECT_ID,
storageBucket: process.env.PROD_STORAGE_BUCKET,
messagingSenderId: process.env.PROD_MESSAGING_SENDER_ID,
appId: process.env.PROD_APP_ID,
measurementId: process.env.PROD_MEASUREMENT_ID,
};
const devConfig = {
apiKey: process.env.DEV_API_KEY,
authDomain: process.env.DEV_AUTH_DOMAIN,
databaseURL: process.env.DEV_DATABASE_URL,
projectId: process.env.DEV_PROJECT_ID,
storageBucket: process.env.DEV_STORAGE_BUCKET,
messagingSenderId: process.env.DEV_MESSAGING_SENDER_ID,
appId: process.env.DEV_APP_ID,
measurementId: process.env.DEV_MEASUREMENT_ID,
};
Then using JavaScript conditional operator, you can condition between the two.
const config = process.env.NODE_ENV === "production" ? prodConfig : devConfig;
This way, you will prevent the mixing of data and other information between development mode app and production or deployed app.
Initializing the Firebase SDK
Initializing the Firebase SDK with the current React app is the first step. To do this, you have to use a method called initializeApp()
and pass the firebaseConfig
as the only argument to this method after defining the config object.
// firebase.js
firebase.initializeApp(firebaseConfig);
Lastly, to test that the Firebase SDK is working with the React app, let us export the firebase
instance from Firebase/firebase.js
file.
export default firebase;
Open App.js
file, import the firebase
instance, and using useEffect
hook let us try to see if it’s initialized or not.
import React, { useEffect } from "react";
// TODO: REMOVE THIS IMPORT STATEMENT BELOW BEFORE PROCEEDING
import firebase from "./Firebase/firebase";
function App() {
// TODO: REMOVE THIS BEFORE PROCEEDING
useEffect(() => {
console.log(firebase);
}, []);
return (
<div>
<h1>React App</h1>
</div>
);
}
export default App;
To see the output of the console statement from the above code snippet, open Developer Tools -> Console tab in the web browser. On the initial render of App
component or the React app, the useEffect
hook is going to trigger.
The object returned from Firebase clearly states that there are no errors with the current Firebase config in a React app.
It is important to notice that Firebase should only be initialized once in the React app. This pattern is called singleton. This initialization should be the top level component in the React components tree.
Conclusion
Here is a summary of what has been done in this tutorial so far.
- Create a React app using
create-react-app
- Create an opinionated directory structure inside React app to manage different components
- Generate Firebase API keys for configuration
- Used environment variables inside a React app to manage keys
- Install
firebase
SDK npm package - Connect Firebase SDK to React app
- Initialize the Firebase SDK
- Why initialize a Firebase instance only once per React app?
👉 Further reading: