Integrating Firebase Authentication with React Router in React 16.3

After many months of React Native development, I’ve been acquainted with building an authentication workflow between Firebase and React Navigation. Lately I was looking to do the same but in ReactJS. The only difference between the web and the native use case is that, on a web app, the user can try to access a navigation state directly via the URL so you need to protect your components. Luckily, React 16.3 now provides a fantastic new Context API that will help us with that.

We first create a Firebase auth context that contains two values:

  • authStatusReported indicates if Firebase has reported the auth status. If the auth status hasn’t been reported yet, you might want to display a loading indicator for your app.
  • isUserSignedIn indicates if the user is signed-in or not.

When the component is mounted, we listen to Firebase onAuthStateChanged in order to set the proper state to our context. Below is the source code of our context provider.

Now we need to create a Protected component (or higher-order component depending on your preferences) that will wrap a component into a consumer of the Firebase authentication context. If the user is signed-in, we return the children, if not, we redirect to the login page.

Of course, you need to wrap your root app component with FirebaseAuthProvider. Using React Context API This is the part that is specific to ReactJS as opposed to React Native.

Everything else is pretty much the same. You can create a Firebase module as below.

You can then sign-in:

and sign-up:

Pretty straightforward no? Will you be using the new React context API to implement your authentication workflow? I’m looking forward to read your thoughts on this topic.

Are you looking for a premium React Native starter kit? You should checkout React Native Elements.

read original article here