Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling firebase auth with react-router

I am building a React + Redux + Firebase app with webpack and am trying to figure out the best way to handle protected routes and redirects. I have tried using onEnter() with setTimeout() like many examples show, but it still ended up flashing the alternate component before redirecting.

Here is what I currently have, and I am trying to come up with a more elegant solution. This mostly works, but an example of when it fails is if I am on /profile and navigate to / in the browser. It seems that because firebase.auth() needs to initialize again, I get a flash of the HomePage component before it switches to Profile.

Firebase is initialized in firebaseClientConfig and I am passing firebase.auth() in to routes.

import { auth } from './firebaseClientConfig';  

...    

export default (
<Route path="/" component={App}>    
 <IndexRoute
  getComponent={(nextState, cb) => {
    auth.onAuthStateChanged((user) => {
      if (!user) {
        return require.ensure([], require => {
          cb(null, require('./components/HomePage').default);
        });
      } else {
        return require.ensure([], require => {
          cb(null, require('./modules/Profile/Profile').default);
        });
      }
    });
  }}
/>
<Route
  path="/profile"
  getComponent={(nextState, cb) => {
    auth.onAuthStateChanged((user) => {
      if (user) {
        return require.ensure([], require => {
          cb(null, require('./modules/Profile/Profile').default);
        });
      } else {
        return require.ensure([], require => {
          cb(null, require('./modules/Login/Login').default);
        });
      }
    });
  }}
/>
</Route>
);

Does anyone have a better way of doing this?

like image 708
Bonitis Avatar asked Sep 06 '16 00:09

Bonitis


People also ask

Can I use Firebase just for authentication?

You can use Firebase Authentication to allow users to sign in to your app using one or more sign-in methods, including email address and password sign-in, and federated identity providers such as Google Sign-in and Facebook Login.


1 Answers

I made a PrivateRoute component and pass it an authenticated prop which I get from the redux store in the component where I use the PrivateRoute

When I login with firebase I put user data in the redux store. So in my case i would map state to props

const mapStateToProps = (state) => ({
    authenticated: !!state.user.uid,
})

And give the authenticated prop to my PrivateRoute component

const PrivateRoute = ({ component: Component, authenticated, path, exact }) => {
  return (
      <Route
          path={path}
          exact={exact}
          render={props =>
            authenticated
              ? <Component {...props} />
              : <Redirect to="/login"/>}
        />
    )
}
like image 50
vhflat Avatar answered Sep 21 '22 15:09

vhflat