The first step is to create a new firebase project, and under Project Overview, create a new web app. It will open a new page that allows you to register your app. You’ll end up with a config object that might look like this.
const firebaseConfig = {
apiKey: 'AIzaXXXXXXXXXXXXXXXXXXXXXXX',
authDomain: 'burger-builder-XXXX.firebaseapp.com',
databaseURL: 'https://burger-builder-XXXXXX.firebaseio.com',
projectId: 'burger-builder-XXXX',
storageBucket: 'burger-builder-XXXX.appspot.com',
messagingSenderId: 'XXXXXXX',
appId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
};
As an alternative, you can also use environment variables in React applications, you only need to prefix them with REACT_APP_
for them to be available from within your code asprocess.env.REACT_APP_<variable name>
. All environment variables should be in a .env
, .env.local
or .env.production
in the root folder of your application.
To Configure Firebase in React
Next, set up firebase in React by creating a firebase.js
file:
Your .env
file may look like this:
REACT_APP_API_KEY=XXXXxxxx
REACT_APP_AUTH_DOMAIN=xxxxXXXX.firebaseapp.com
REACT_APP_DATABASE_URL=https://xxxXXXX.firebaseio.com
REACT_APP_PROJECT_ID=xxxxXXXX
REACT_APP_STORAGE_BUCKET=xxxxXXXX.appspot.com
REACT_APP_MESSAGING_SENDER_ID=xxxxXXXX
We’ve set Firebase up in React, but we’re not using it anywhere. An easy way to do so is by creating a Firebase instance with the Firebase class, and then importing that instance in every React component where it’s needed. This is not the ideal way for 2 reasons:
- It would make your application more error-prone. Firebase should be initialized as a singleton (once) in React applications, and by exposing it in every component that needs it, you might end up with multiple instances
- It makes it harder to test your components
The more ideal way to create one Firebase instance in your application is with the help of React’s Context API:
import React, { createContext } from "react";const FirebaseContext = createContext(null);export default FirebaseContext;
createContext()
provides two new components; FirebaseContext.Provider
provides a single Firebase instance at the top-level of your application component tree — index.js
. FirebaseContext.Consumer
is available to get the Firebase instance in any component when needed.
Authentication with Firebase Authentication API
On to the main point of this article; communicating with Firebase through the Firebase Authentication API and our Firebase instance. We’ll be looking at how to authenticate users with email/password, Google, Facebook, and GitHub.
Authenticating with Email/Password
First, we need to activate the email/password authentication provider on the Firebase console. On your project’s Firebase dashboard, you can find a menu item that says “Authentication”. Select it and click the “Sign-In Method” menu item afterward. There you can enable the authentication with Email/Password:
To implement the email/password auth provider in the application, we need to import and instantiate the package responsible for all authentication from Firebase in firebase/firebase.js
. Then call the functions to create, sign in and out users, and update and reset their password:
...
import "firebase/auth";const firebaseConfig = {
...
};class Firebase {
constructor() {
...
this.auth = app.auth();
} createUserWithEmailAndPassword = (email, password) =>
this.auth.createUserWithEmailAndPassword(email, password); signInWithEmailAndPassword = (email, password) =>
this.auth.signInWithEmailAndPassword(email, password); signOut = () => this.auth.signOut();
passwordReset = (email) => this.auth.sendPasswordResetEmail(email); passwordUpdate = (password) => this.auth.currentUser.updatePassword(password);}export default Firebase;
When called, all functions are run asynchronously to be resolved later with either a success or a failure. For example, the Firebase API will return an error if you try signing in a user that does not already exist.
Authenticate with Google
In the same vein, in order to enable Google authentication in your Firebase React application, the Google sign-in method needs to be enabled in your Firebase console.
The Firebase Authentication API also provides functions that allow users to sign in or register with a provider. Depending on whether you’d like the form to appear as a popup or a new page, you can use signInWithPopup
or signInWithRedirect
. We first need to instantiate the provider — in our case, google — then call the function to authenticate with it. In the example below, I used the function to sign in with a popup. Note that it may make for a better user experience to sign in with a redirect in mobile devices.
In trying to prevent duplicating code, I created a function the runs a switch on the passed provider then finally signs in with the passed provider. This way, I only call this.auth.signInWithPopup
once.
Then in the component, attach a handler to the “Google” button and call this function, passing in “google” as the argument.
Authenticate with Facebook
Authenticating with Facebook is very similar to authenticating with Google, at least in the code. The main difference is that you need to set up a Facebook developer account and create an app there. You’ll receive an application ID and secret which you then provide Firebase to enable the connection.
To create a Facebook developer account, sign in to your Facebook account here. Go to “My Apps”, and create an app. After creating your new app, you’ll be taken to the app dashboard. From there, your app ID and secret should be under Basic settings
Copy and paste your app ID and secret into your Firebase console after enabling the Facebook sign-in method, then also make sure to add the provided OAuth redirect URI to your Facebook app configuration.
From here, it's the same as before; just instantiate your Facebook provider with new firebase.auth.FacebookAuthProvider()
and pass that into the sign-in function.
Authenticate with Github
Similar to Facebook, we first need to register our application on Github as a developer application and get the app ID and secret, while providing the authorized callback URL provided by Firebase. Everything else is the same; instantiate the Github provider and pass that into the sign-in function:
const githubProvider = new firebase.auth.GithubAuthProvider();return this.auth.signInWithPopup(githubProvider);
Don’t forget to attach the function to the Github sign-in button in your Login component.
Conclusion
Firebase is a simple, yet powerful tool that allows developers to focus on building applications and worry less about handling the infrastructure. Other than handling authentication, Firebase can also handle asset storage, database management, and hosting, but that’s just the surface. Explore more of Firebase can do here.
One thing that’s worth mentioning again when introducing Firebase to your React applications is to make sure that Firebase is initialized as a singleton. This boosts the integrity of your app and makes it a little less error-prone.
Next Steps
Now that your application handles user authentication, a good next step might be setting up protected routes in the system to allow users to see the information that is specific to them. In our application, for example, a protected route could be a profile page where users might see their past orders, and update their profile info (like their password).