React ~ Router ~ Protected Routes - rohit120582sharma/Documentation GitHub Wiki

Often times when building a web app, you’ll need to protect certain routes in your application from users who don’t have the proper authentication.

Though React Router doesn’t provide any functionality for this out of the box, we can create our PrivateRoute implementation which handles our own specific use cases.

Here are the requirements for our PrivateRoute component:

  • It has the same API as <Route />
  • It renders a <Route /> and passes all the props through to it
  • It checks if the user is authenticated. If they are, it renders the “component” prop. If not, it redirects the user to /login
/* -----------------------
PrivateRoute.js
----------------------- */
function PrivateRoute({ component: Component, ...rest }) {
    return (
        <Route
            {...rest}
            render={(props) => {
                return (fakeAuth.isAuthenticated === true)
                    ? <Component {...props} />
                    : <Redirect to={{
                          pathname: '/login',
                          state: { from: props.location }
                      }} />
            }} />
    );
);
/* -----------------------
App.js
----------------------- */
import React from 'react';
import { Switch, Route } from 'react-router-dom';

import Public from './Public';
import Protected from './Protected';
import PrivateRoute from './PrivateRoute';

class App extends React.Component {
    render(){
        return (
            <Router>
                <div>
                    <ul>
                        <li><Link to="/public">Public Page</Link></li>
                        <li><Link to="/protected">Protected Page</Link></li>
                    </ul>
                    <Switch>
                        <Route path="/public" component={Public} />
                        <Route path="/login" component={Login} />
                        <PrivateRoute path="/protected" component={Protected} />
                    </Switch>
                </div>
            </Router>
        );
    }
}
⚠️ **GitHub.com Fallback** ⚠️