React Router 6: Private Routes (alias Protected Routes)
Tags: react, abotwrotethis
Published: 2023-04-07 17:02:02

Are you building a React-based web application that requires authentication and authorization? Are you looking for an easy and efficient way to implement a secure user flow? Then you're in the right place! 

React Router 6 has introduced a new concept of private routes, also known as protected routes, that enables you to guard your sensitive routes from unauthorized access. In this blog post, we'll explore the basics of private routes and how to implement them in your React application. 

## What are Private Routes?

Private routes are those routes that require a user to be authenticated or authorized to access them. These routes often contain sensitive information, such as user profile pages or payment processing pages, and it's important to protect them from unauthorized access. 

In a typical React application, routing is handled by React Router. React Router provides a set of components that allow you to define routes and navigate between them. However, until now, there was no built-in mechanism for securing routes that require authentication or authorization. 

With the introduction of private routes in React Router 6, you can now wrap your sensitive routes in a custom component that checks the authentication status of the user before rendering the component. 

## Implementing Private Routes in React Router 6

To implement private routes in your React application, follow these steps:

### 1. Check the authentication status of the user

The first step in implementing private routes is to determine whether the user is authenticated. There are several ways to do this, but the most common method is to store the authentication status in a global state using a state management library like Redux or MobX. 

For the purposes of this example, we'll assume that the authentication status is stored in a Redux store. We'll create a selector function that checks the authentication status and returns a boolean value:

```jsx
const isAuthenticated = state => state.auth.isAuthenticated;
```

### 2. Create a PrivateRoute component

Next, we'll create a custom PrivateRoute component that checks the authentication status before rendering the component. This component will accept a component prop, which is the component to render if the user is authenticated and a redirect prop, which is the route to redirect to if the user is not authenticated. 

```jsx
import { Route, Redirect } from 'react-router-dom';
import PropTypes from 'prop-types';
import { useSelector } from 'react-redux';

const PrivateRoute = ({ component: Component, redirect: pathRedirect, ...rest }) => {
  const isAuthenticated = useSelector(state => state.auth.isAuthenticated);

  return (
    <Route
      {...rest}
      render={({ location }) =>
        isAuthenticated ? (
          <Component />
        ) : (
          <Redirect
            to={{
              pathname: pathRedirect,
              state: { from: location },
            }}
          />
        )
      }
    />
  );
};

PrivateRoute.propTypes = {
  component: PropTypes.elementType.isRequired,
  redirect: PropTypes.string.isRequired,
};

export default PrivateRoute;
```

In the code above, we're using the useSelector hook to access our authentication state from the Redux store. We then use the Route component from React Router to render the component if the user is authenticated or redirect to the specified route if the user is not authenticated.

### 3. Use the PrivateRoute component

Finally, we'll use our custom PrivateRoute component in place of a regular Route component. Any routes that require authentication or authorization can be wrapped in the PrivateRoute component, as shown below:

```jsx
import { Switch } from 'react-router-dom';
import PrivateRoute from './PrivateRoute';
import HomePage from './HomePage';
import ProfilePage from './ProfilePage';
import LoginPage from './LoginPage';

const App = () => {
  return (
    <Switch>
      <PrivateRoute exact path="/" redirect="/login" component={HomePage} />
      <PrivateRoute path="/profile" redirect="/login" component={ProfilePage} />
      <Route path="/login" component={LoginPage} />
      <Route path="*" component={() => '404 Not Found'} />
    </Switch>
  );
};

export default App;
```

In the example above, we have two private routes: one for the home page and one for the user profile page. These routes will redirect to the login page if the user is not authenticated.

## Conclusion

Private routes, also known as protected routes, are an essential feature for any React-based web application that requires authentication and authorization. React Router 6 has made it easy to implement private routes in your application, allowing you to guard your sensitive routes from unauthorized access. By following the steps outlined in this blog post, you can quickly and easily secure your routes and provide a seamless user experience for your users.