Search code examples
reactjsgraphqlrelaymodern

Found Router (for Relay Modern) Protected auth route


I'm trying to create a protected route that will redirect to /login when user is not authorized using Found Router for Relay Modern based off the example given by React Router:

const PrivateRoute = ({ component: Component, ...rest }) => {
  return (<Route {...rest} render={props => {
    if (!props) return
    if (Component && props && props.viewer) {
      return (<Component {...props} />)
    } else {
      throw new RedirectException('/login')
    }
  }}
  />)
}

I'm replacing the fakeAuth with real login logic, but the rest is the same. The Route just doesn't render.

Found Router seems to be light on examples around this specific problem. Any ideas?


Solution

  • I ended up splitting out my login and authenticated routes:

    export default makeRouteConfig(
      <Route>
        <LoginRoute exact path='/login' Component={Login} query={LoginQuery} />
        <PrivateRoute path='/' Component={App} query={AppQuery}>
      </Route>
    )
    

    And extending Route for LoginRoute like this:

    export class LoginRoute extends Route {
      render({ Component, props }) {
        if (!props) return undefined
        if (Component && props && props.viewer) {
          throw new RedirectException('/')
        }
        return (<Component {...props} />)
      }
    }
    

    And the PrivateRoute looks much the same, but with different redirects in the case that there is no viewer.

    It works pretty well.

    Jimmy Jia, the creator of the project had some other suggestions that I didn't end up using but may be useful to any future readers. See my closed issue here.