One of the most common requirements in web apps is to prevent unauthorized access to certain routes. For example, you may need to allow only signed-in users to visit the _/profile _route in your app. This task may seem daunting to beginners.

This tutorial requires familiarity with react context and react-hooks. If you know how to setup firebase and firebase auth in a react app, its good, but if you don’t, it’s not a problem. You can follow along and do that later. But, knowledge of the two things mentioned above are kind of must.

We will create a Firebase auth provider which will allow us to consume the authentication data anywhere in the app. We create AuthContext with the following default values

createContext( {userDataPresent:false, user:null} )

The idea is to update_ userDataPresent_ and user values as the authentication state changes in our app. This is done by updating the state using the _useState _hook. The _onAuthStateChanged _method provided by Firebase is used to listen for the changes in authentication state and if a change occurs, update the state accordingly (example below). Changing the state changes the context value that’s being passed down to the consumers and the consumers are able to react accordingly. Since our _FirebaseAuthContext _ component will sit at the highest level in the component tree, any changes made to the state(and in turn, the context value) will force re-render of the rest of the components. Which means, signing out from protected routes will force a redirect. All of this can be seen happening in the example below.

#reactjs #react-hook #react #firebase #firebase

How to Create Protected Routes in a React app with Firebase and react-router
31.10 GEEK