1

In a React SPA, I have a collection of "pages" under the /src/pages/ folder.

The entry point page is an index.js file under the /src/ folder, where I define a router const like this:

const routing = (
  <Router>
    <div>
      <Switch>
        <Route path="/signIn" component={SignIn} />
        <Route exact path="/" component={Homepage} />
        <Route path="/page1" component={Page1} />
        <Route path="/page2" component={Page2} />
        <Route path="/page3" component={Page3} />
        <Route component={NotFound} />
      </Switch>
    </div>
  </Router>

It works great and all. All pages are navigable like "https://mysuperapp.com/page2" and it will render the Page2 React component.

Concerns arise when I incorporate user session management (log in, log out). If a user is not logged in the app, all pages should automatically redirect to the /signIn page. And viceversa, if a user is already logged, if the /signIn page is accessed, it should automatically redirect to the root homepage.

Right now I have implemented this by adding the following code to all the pages, right after the render() method is declared in the component, like this:

class Page2 extends React.Component {
  render() {
    if (UserProfile.getUserSessionStatus() !== "logged") {
      this.props.history.push("/signIn");
    }
  }

  return (
    JSX code to be rendered here...
    ...

This works, but it feels like a cheap workaround used by someone who is just learning React, not by a professional.

For a proof of concept it works, but I would never dare to use such a thing in a production environment.

So, what's the right, best-practices-aligned way to accomplish this?

Rikai no hōhō
  • 737
  • 1
  • 7
  • 13
  • Possible duplicate of [What is the best way to redirect a page using React Router?](https://stackoverflow.com/questions/45089386/what-is-the-best-way-to-redirect-a-page-using-react-router) – Lesair Valmont Feb 23 '19 at 13:36

1 Answers1

5

One possible approach is to create a Higher Order component(HOC) and use it for protecting any routes that require login.


const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => (
    UserProfile.getUserSessionStatus() === "logged"
      ? <Component {...props} />
      : <Redirect to='/login' />
  )} />
)

And then use like this

.....
<PrivateRoute path='/page1' component={Page1} />
.......

Hope this helps!

Rowland
  • 1,728
  • 1
  • 12
  • 19