In many web applications, it's required to have certain routes available only to authenticated users. React, being a popular JavaScript library for building user interfaces, provides a flexible way to handle private authenticated routes.

Why we need private routes?

Private routing allow us to restrict access to certain routes or components based on user authentication or authorization. It ensures that only logged in users can access protected routes or components.

How to create private routes in React?

In this article, we'll learn how to implement private authenticated routes in React using an example.

To begin, let's assume that we have an authentication system set up and can determine whether a user is authenticated or not. We'll create a simple example with two routes: a public home page and a private dashboard page.

Step 1: Set up the React Router

First, we need to install react-router-dom package in our project. This package allows us to handle routing in React. We can install it using npm or yarn:

npm install react-router-dom

Next, we set up the basic routing structure in our application. Let's create a file called App.js and import the necessary dependencies:

import React from 'react';
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';

const App = () => {
  return (
    <Router>
      <div>
        {/* Our routes here */}
      </div>
    </Router>
  );
};

export default App;

 

Step 2: Create PrivateRoute Component

In order to create private authenticated routes, we'll define a custom component called PrivateRoute that acts as a wrapper around the original Route component from react-router-dom. This component will render the provided component only if the user is authenticated; otherwise, it will redirect them to a login page.

Let's create an another new file called PrivateRoute.js and add the following code:

import React from 'react';
import { Route, Redirect } from 'react-router-dom';

const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => {
  return (
    <Route
      {...rest}
      render={(props) =>
        isAuthenticated ? (
          <Component {...props} />
        ) : (
          <Redirect to="/login" />
        )
      }
    />
  );
};

export default PrivateRoute;

We can use Firebase, Auth0, or our own backend API for authentication. We also have to handle authentication and maintain the user's login state using appropriate mechanisms like tokens, session storage, or cookies.

 

Step 3: Create Home, Dashboard and Login components

Let's create few components for using it our App and redirect users based on the private routes.

We will create Home, Dashboard and Login components.

  • Home Component
import React from 'react';

const Home = () => {
  return <h1>Home</h1>;
};

export default Home;
  • Dashboard component
import React from 'react';

const Dashboard = () => {
  return <h1>Dashboard</h1>;
};

export default Dashboard;
  • Login Component
import React from 'react';

const Login = () => {
  return (
    <div>
      <h1>Login Page</h1>
      {/* login form */}
    </div>
  );
};

export default Login;

 

Step 4: Implement Private Authenticated Routes

Now that we have our PrivateRoute component, let's use it to create private authenticated routes in our App.js file.

Import PrivateRoute component and our other components Home, Dashboard and Login in App.js.

import React from 'react';
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
import PrivateRoute from './PrivateRoute';
import Home from './components/Home';
import Dashboard from './components/Dashboard';
import Login from './components/Login';

const App = () => {
  const isAuthenticated = true; //state determined from actual authentication logic

  return (
    <Router>
      <div>
        <Route exact path="/" component={Home} />
        <PrivateRoute
          path="/dashboard"
          component={Dashboard}
          isAuthenticated={isAuthenticated}
        />
        <Route
          path="/login"
          render={() =>
            isAuthenticated ? <Redirect to="/dashboard" /> : <Login />
          }
        />
      </div>
    </Router>
  );
};

export default App;

In the example above, we have a boolean variable isAuthenticated which represents whether the user is authenticated or not. In a real-world scenario, we have the value coming from our actual authentication logic.

The PrivateRoute component is used to wrap the /dashboard route, making it private and accessible only to authenticated users. Do not forget to pass the isAuthenticated to PrivateRoute component. 

So, this is how it works. If users are not authenticated and try to access the/dashboard, they will be redirected to the login page. Our Homepage is not private route and accessible to all users without authentication.

That's it! With these steps, we have successfully implemented private authenticated routes in React. 

This is a basic version of the implementation. To enhance user experience, we can render a loading screen while checking if the user is authenticated or secure specific routes with private access.