Private routes in React

Almost every app will have routes that you want to keep private from users that haven’t registered. Here’s a simple, scalable way to build and implement a reusable PrivateRoute component in React.

import React, { useContext } from 'react';
import { Route, Redirect } from 'react-router-dom';
import AuthContext from '../../context/auth/authContext';

const PrivateRoute = ({ component: Component, ...rest }) => {
  const authContext = useContext(AuthContext);
  const { isAuthenticated, loading } = authContext;

  return (
    <Route
      {...rest}
      render={props =>
        !isAuthenticated && !loading ? (
          <Redirect to='/login' />
        ) : (
          <Component {...props} />
        )
      }
    />
  );
};

export default PrivateRoute;

This PrivateRoute component from a contact manager app I’m building returns a Route that redirects users to the login page from any other route if they have not been authenticated in the login process.

If the user is authenticated, however, the component associated with the route they’re trying to access is rendered with all the pertinent props passed in.

The component is easily implemented in my App.js file like so:

<PrivateRoute exact path='/' component={Home} />

Do you have a different or more elegant way of building a reusable component for private routes? Please share in the comments!

Show Comments

Get the latest posts delivered right to your inbox.