How to setup a React App with a Firebase project

Published on Jun 5, 2020

8 min read

FIREBASE

cover

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.

ss1

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).

ss2

Add an initial modification of src/App.js file to the file code snippet.

1import React from 'react';
2
3function App() {
4 return (
5 <div>
6 <h1>React App</h1>
7 </div>
8 );
9}
10
11export default App;

This modification is going to lead to the following change in a web browser window.

ss3

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

ss4

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.

ss5

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.

ss12

The Settings page opens as shown below.

ss13

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.

ss16

Next, there is going to be a prompt about adding the name of the web app. Enter a name.

ss14

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.

ss15

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.

1// firebase.js
2
3import * as firebase from 'firebase/app';
4
5const firebaseConfig = {
6 apiKey: process.env.DEV_API_KEY,
7 authDomain: process.env.DEV_AUTH_DOMAIN,
8 databaseURL: process.env.DEV_DATABASE_URL,
9 projectId: process.env.DEV_PROJECT_ID,
10 storageBucket: process.env.DEV_STORAGE_BUCKET,
11 messagingSenderId: process.env.DEV_MESSAGING_SENDER_ID,
12 appId: process.env.DEV_APP_ID,
13 measurementId: process.env.DEV_MEASUREMENT_ID
14};

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`.
1const prodConfig = {
2 apiKey: process.env.PROD_API_KEY,
3 authDomain: process.env.PROD_AUTH_DOMAIN,
4 databaseURL: process.env.PROD_DATABASE_URL,
5 projectId: process.env.PROD_PROJECT_ID,
6 storageBucket: process.env.PROD_STORAGE_BUCKET,
7 messagingSenderId: process.env.PROD_MESSAGING_SENDER_ID,
8 appId: process.env.PROD_APP_ID,
9 measurementId: process.env.PROD_MEASUREMENT_ID
10};
11
12const devConfig = {
13 apiKey: process.env.DEV_API_KEY,
14 authDomain: process.env.DEV_AUTH_DOMAIN,
15 databaseURL: process.env.DEV_DATABASE_URL,
16 projectId: process.env.DEV_PROJECT_ID,
17 storageBucket: process.env.DEV_STORAGE_BUCKET,
18 messagingSenderId: process.env.DEV_MESSAGING_SENDER_ID,
19 appId: process.env.DEV_APP_ID,
20 measurementId: process.env.DEV_MEASUREMENT_ID
21};

Then using JavaScript conditional operator, you can condition between the two.

1const 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.

1// firebase.js
2
3firebase.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.

1export 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.

1import React, { useEffect } from 'react';
2
3// TODO: REMOVE THIS IMPORT STATEMENT BELOW BEFORE PROCEEDING
4
5import firebase from './Firebase/firebase';
6
7function App() {
8 // TODO: REMOVE THIS BEFORE PROCEEDING
9
10 useEffect(() => {
11 console.log(firebase);
12 }, []);
13
14 return (
15 <div>
16 <h1>React App</h1>
17 </div>
18 );
19}
20
21export 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.

ss17

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:


More Posts

Browse all posts

Aman Mittal author

I'm a software developer and a technical writer. On this blog, I write about my learnings in software development and technical writing.

Currently, working maintaining docs at 𝝠 Expo. Read more about me on the About page.


Copyright ©  2019-2024 Aman Mittal · All Rights Reserved.