Create protected route in React using Firebase and react-router

Tram Ho

One of the most common requirements of web applications is to prevent unauthenticated access to certain pages. For example, we only allow logged-in users to access facebook.com/profile .

In this article let’s learn how to use Firebase and react-router to create proctected routes with react. To do this requires you to know a little about react context and react-hooks.

First we need to create a Firebase auth provider, after creating it, we can use it to get data after logging in anywhere in the application. createContext( {userDataPresent:false, user:null} )

The idea here is to update userDataPresent and user when the validation state changes in the application. To update the state we use a hook called useState. The onAuthStateChanged function provided by Firebase is used to listen for the authentication state change, meaning that when there is a change in authentication data, the function will be called.

Changing the state will change the value of the context that is passed on to Consumers and Consumers can be aware. Since the FirebaseAuthContext component is placed at the top level in the tree component, any change to the state will re-render the remaining components. For example, when you log out of a page that requires authentication, it will redirect.

Note here that we will store the value returned by onAuthStateChanged listener in the state after initialization. The purpose is to allow us to unsubcribe when the component is unmounted.

The changeState function is called whenever the listener receives new validation data. user contains the user information, null when the user is logged out.

The protectedRoute is the consumer of the context we created earlier, used to wrap the react-router’s Route component. The goal is to return the Redirect if the user is not logged in, otherwise return the Route so that the route is accessible but the route is protected. userDataPresent is used to display the spiner denoting the load. Now to use ProtectedRoute, we can do the following:

Simple as that, thank you for taking the time to read the article

This source: https://medium.com/swlh/firebase-authentication-and-react-protecting-your-routes-18d6da04b4c3

Share the news now

Source : Viblo