0

I am trying to create a server-side auth guard for react route. My flow is like... Whenever a route is hit on the front-end, a backend call is made to check if the user's session is present in the Database (since we store session in the database to keep track of sessions).

Here is my app component code:

    export default function App() {
  const routeComponents = routes.map(({ path, component }) => <AuthenticatedRoute exact path={path} component={component} props={'exact'} key={path} />);

  return (
    <div>
      {window.location.origin === constant.PRODUCTION_DOMAIN_NAME && <Route
        path="/"
        render={({ location }) => {
          if (typeof window.ga === 'function') {
            window.ga('set', 'page', location.pathname + location.search);
            window.ga('send', 'pageview');
          }
          return null;
        }}
      />}
      <Switch>
        <Route path="/login" component={LoginPage} />
        {routeComponents}
      </Switch>
      <ToastContainer autoClose={constant.TOASTER_FACTOR} closeButton={false} hideProgressBar />
    </div>
  );
}

App.propTypes = {
  component: PropTypes.any,
};

I have segregated the authenticated route into a separate class component like:

    export class AuthenticatedRoute extends React.Component {

  componentWillMount() {
    //I call backend here to check if user is authenticated by session Id in DB
  }



  render() {
    const { component: Component, ...rest } = this.props;
    return (
      <Route exact {...rest} render={(props) => this.state.isAuthenticated ? <Component {...props} /> : <Redirect to="/login" />} />
    );
  }
  }

AuthenticatedRoute.propTypes = {
  component: PropTypes.any,
....

};

const mapStateToProps = (state) => ({
  reducer: state.get('myReducer'),

});

export default connect(mapStateToProps, { func })(AuthenticatedRoute);

But I face an issue where the login page is redirected twice. Could someone let me know a better approach for this?

Kousika Ganesan
  • 539
  • 1
  • 6
  • 22
  • the reason for redirecting twice is that, before the API request returns a response you are making a redirect, check this question on how to handle authentication https://stackoverflow.com/questions/47627818/performing-authentication-on-routes-with-react-router-v4/47628941#47628941 – Shubham Khatri Apr 19 '18 at 06:56
  • @ShubhamKhatri, when I listen to the props in the component will mount and made a history.push. It is working. But only for the second time. Initially nothing gets stored in the db. – Kousika Ganesan Apr 19 '18 at 11:14

0 Answers0