Authentication workflow in react/redux
<p>I am trying to setup a new front-end project using react, react-router and redux and I'm stumbling on setting up a login workflow that works well and with many pages. </p>

<p>Here is the logic that I want to have: </p>

<ol>
<li>Have a variable in the redux store that says if I'm logged in or not. To simplify let's say that we have <code>logged: true/false</code>. </li>
<li>When <code>logged</code> is set to true from the login page, redirect to the page we were redirected from, or redirect to <code>/</code> if not defined. The previous location is stored in <code>nextPathname</code>.  </li>
<li>When <code>logged</code> is set to <code>false</code> in a component that requires auth, redirect to <code>/</code>. </li>
</ol>

<p>My main problem with this workflow is that I want to dispatch an action (set the logged value) and then do a redirection.</p>

<p>Here are a few alternatives that I have explored: </p>

<ol>
<li>Check if <code>logged==true</code> in my login component's <code>componentWillReceiveProps</code> and redirect if it's the case. This works well for the login workflow but if I have to implement such a logic for the logout component, I have to do it for each component that requires auth. (Mixins don't work thanks to ES6 react components...). </li>
<li>Handle the redirections in a middleware: when the action is about login, run the action and then redirect. However I don't know if this is a best practice or not. </li>
</ol>

<p>So my question is: how do I make the auth work without too much overhead on all pages that are restricted? </p>

<p>A bit of code: </p>

<p>app.js: </p>

<pre class="lang-js prettyprint-override"><code>function requireAuth(nextState, replace) {
    if(store.getState().Login.logged === false) {
        replace({
            pathname: "/login",
            state: { nextPathname: nextState.location.pathname }
        });
    }
}
const history = syncHistoryWithStore(browserHistory, store);
ReactDOM.render(
    &lt;Provider store={store}&gt;
        &lt;Router history={history}&gt;
            &lt;Route path="/" component={Archives} onEnter={requireAuth}&gt;&lt;/Route&gt;
            &lt;Route path="/login" component={LoginComponent}&gt;&lt;/Route&gt;
        &lt;/Router&gt;
    &lt;/Provider&gt;,
    document.getElementById("app")
);
</code></pre>

<p>The LoginComponent: </p>

<pre class="lang-js prettyprint-override"><code>class LoginComponent extends React.Component&lt;LoginProps, any&gt; {
    componentWillReceiveProps(newProps) {
        if(newProps.logged) {
            let nextPath = "/";
            const {location, history} = newProps;
            if (location.state &amp;&amp; location.state.nextPathname) {
                nextPath = location.state.nextPathname;
            }
            history.pushState({}, nextPath);
        }
    }
    render() {
       return &lt;div&gt;This is a login form&lt;/div&gt;
    }
}
</code></pre>