Search code examples
reactjsreact-routerreact-router-redux

React router force to another page if a variable doesn't exist


Was wondering if react router has a way to preempt a route to check for a variable, e.g. session variable, and if that variable doesn't exist, to route to somewhere else or not at all? This question is tied into the browser history.

My scenario is this-- when a user logs in, there are certain routes exposed. If that user logs out, those routes are not exposed on the screen. However, since I have browser history, a logged out user is able to see the restricted routes by pressing the back button. Since I can not clear the browser history, I was thinking that if a restricted route gets called-- whether through router or through history--that there is a way to preempt the call and check if the user is logged in before allowing that route to proceed.

Any suggestions would be appreciated.


Solution

  • I handle this in my app with an AuthenticatedRoute component:

    import React from 'react';
    import { withRouter } from 'react-router'
    import { Route, Redirect } from 'react-router-dom';
    
    const AuthenticatedRoute = ({component: Component, ...rest}) => {
        return session.VARIABLE
            ? <Route render={ props => <Component {...props} {...rest} />} />
            : <Redirect to="/login" />;
    };
    
    export default withRouter(AuthenticatedRoute);
    

    Usage:

    <AuthenticatedRoute path="/path" component={MyComponent} />
    

    If the variable exists, it returns a normal Route, but if it doesn't exist it returns a Redirect component which will immediately redirect the user to the given path.