I have a very simple app that lets you log in and then displays a dashboard. The design process with React and Redux is very simple :

  • I have two React components : Login and Dashboard
  • I store a boolean isAuthenticated in my state tree

Now some remarks :

  • The Login component can only be seen if isAuthenticated is false
  • The Dashboard component can only be seen if isAuthenticated is true
  • A button in the Login component sets isAuthentication to true
  • A button in the Dashboard component sets isAuthentication to false

How should I implement this in React ? There is at least two possibilities :

  • using routing : / redirects to /login if authenticated or /dashboard if not. Also /login redirects to /dashboard if authenticated and /dashboard redirects to /login if not authenticated
  • introduce an App component that renders either Login or Dashboard depending on isAuthenticated

Here is the implementation of the second proposal :

const Login = (props) => (
  <div className="login">
    <p>Login page</p>
    <input type="button" value="Log in" onClick={props.toggleAuthentication}/>
const Dashboard = (props) => (
  <div className="dashboard">
    <p>Dashboard page</p>
    <input type="button" value="Log out" onClick={props.toggleAuthentication}/>
class App extends React.Component {
    this.state = {isAuthenticated: false}
    this.setState({isAuthenticated: !this.state.isAuthenticated})
  render() {
      return <Login toggleAuthentication={()=>this.toggleAuthentication()}/>
    } else {
    return <Dashboard toggleAuthentication={()=>this.toggleAuthentication()}/>
  <App />,
| improve this question | | | | |

I think the generally preferred react-router way to do this would be to have an onEnter hook that checks to see if you're logged in. If you're not, you get redirected to Login.

I've personally done it the second way you described, and while it worked, it did leak some information about URL structure to a non-authenticated user.

If you're not using react-router, you may want to use your second approach. If you are using react-router, have a look at their auth flow example:


| improve this answer | | | | |

The onEnter() approach suggested by @dannyid seems simple and efficient, although I've never tried it as of now.

I've recently stumbled upon this great article, describing another way of implementing authentication with higher order components: http://engineering.blogfoster.com/higher-order-components-theory-and-practice/

| improve this answer | | | | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.