How to handle user logged in state in React JS and Firebase?

544 Views Asked by At

I'm developing a web app using React JS and Firebase. I want the following behavior to work in my app.

On the sign-in page, there is a checkbox "Keep me signed in". If the user did NOT mark that checkbox, the user should be signed out automatically when the tab/browser is closed. If the user MARKED the checkbox "Keep me signed in", the user will not be signed out unless the user clicked on the "Sign out" button in the dashboard. Further, the user should be redirected to the Dashboard page if the user is logged in. If the user is not logged in, the user should be redirected to the sign-in page.

And, the user should not be able to go to the pages by manually typing the URLs.

Here is a part of my current index.js file.

const browserHistory = createBrowserHistory();

firebase.auth().onAuthStateChanged(user => {
  user ? browserHistory.push("/dashboard") : browserHistory.push("/signin");
});

ReactDOM.render(
  <Router history={browserHistory}>
    <Switch>
      <Theme>
        <Route exact path="/signin" component={SignIn} />
        <Route path="/dashboard" component={Dashboard} />
        <Redirect to="/" />
      </Theme>
    </Switch>
  </Router>,
  document.getElementById('root')
);

Here, my problem is, the user can go back after redirecting. I think this is not the correct way to do this.

So, please help me to get this behavior done. Answer with code example is so much appreciated.

1

There are 1 best solutions below

2
Drew Reese On

history.replace is the functional equivalent to Redirect component.

replace(path, [state]) - (function) Replaces the current entry on the history stack

firebase.auth().onAuthStateChanged(user => {
  browserHistory.replace(user ? "/dashboard" : "/signin");
});

What you'll also likely want to do upon successful login is to do another redirect to the dashboard.