0

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.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Sennen Randika
  • 1,566
  • 3
  • 14
  • 34

1 Answers1

0

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.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Same behavior as it currently has. User can click on BACK button on the browser and it goes back to the "/" and nothing is rendered since no route has been set to "/" path. – Sennen Randika Apr 14 '20 at 06:47
  • @SennenRandika Maybe your redirect should go to somewhere your router handles? App usually either have a final catch-all "404" route, or they "push" the user back to a known route by redirecting them there. I'd suggest creating a "home" component to render on "/", have that route be the "starting" point, move the auth redirect logic there. – Drew Reese Apr 14 '20 at 06:49