How to Build Private Routes in React with React Router

In this post, you will learn how to build protected routes in React js app using the React router dom library and grant access to only logged-in users.

Route protection is significant, protected routes give access to only authorized users. It simply means users can access the specific route when met with certain conditions.

Private Routes in React are also known as protected routes. If the user is not logged in, he can not access the dashboard or the user profile page. These pages or routes are protected using certain logic, it requires the user to authenticate first then the user can access or visit a route.

We will build a React app with public and private route components using router dom APIs. Users can access the public routes and cannot access the private route user will redirect to another URL when accessing the protected route in our react app.

React Protect or Secure Private Routes with React Router Example

  • Step 1: Set Up React Project
  • Step 2: Add Router DOM Library
  • Step 3: Build New Components
  • Step 4: Create Routes Navigation
  • Step 5: Secure Private Routes
  • Step 6: Protect Multiple Routes
  • Step 7: Run Development Server

Set Up React Project

On the terminal, type the command for generating new react app, then enter into the project folder.

npx create-react-app react-verse
cd react-verse

Add Router DOM Library

You have to execute the following commands from the console and install react-router and bootstrap packages in react app.

npm i react-router-dom bootstrap

Build New Components

Navigate to the app folder, you have to form the new components/Home.js file and add the given code to the file.

import React from 'react'

function Home() {
  return (
    <div className="card mt-5 text-center">
      <div className="card-body">Home</div>
    </div>
  )
}

export default Home

Next, make the components/Profile.js and place the provided code to the file.

import React from 'react'

function Profile() {
  return (
    <div className="card">
      <div>Profile</div>
    </div>
  )
}

export default Profile

Now, you need to create components/Dashboard.js and put the given code into the file.

import React from 'react'

function Dashboard() {
  return (
    <div className="card mt-5 text-center">
      <div className="card-body">Dashboard</div>
    </div>
  )
}

export default Dashboard

Create Routes Navigation

We will now define the navbar, therefore make the components/NavBar.js in this file we will define the links using the Link module.

import { Link } from 'react-router-dom'

const NavBar = () => {
  return (
    <nav className="col-12">
      <div>
        <Link to="/">Home</Link>
      </div>
      <div>
        <Link to="/profile">Profile</Link>
      </div>
      <div>
        <Link to="/dashboard">Dashboard</Link>
      </div>
    </nav>
  )
}

export default NavBar

Secure Private Routes

To protect the routes, create the PrivateRoute.js file in the components/ folder.

The private route component takes isAuthenticated, and children parameters, It redirects to home page if the user is authenticated else it returns the private routes.

import React from 'react'
import { Navigate } from 'react-router-dom'

function PrivateRoute({ isAuthenticated, children }) {
  if (!isAuthenticated) {
    return <Navigate to="/" replace />
  }
  return children
}

export default PrivateRoute

Protect Multiple Routes

Open App.js, in this file, you have to add the suggested code. The following code example is used for protecting the multiple routes in react.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
import NavBar from "./components/NavBar";
import Home from "./components/Home";
import Profile from "./components/Profile";
import Dashboard from "./components/Dashboard";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import PrivateRoute from "./components/PrivateRoute";


export default function App() {
  const [isAuthenticated, setLoggedin] = React.useState(null);

  const login = () => {
    setLoggedin(true);
  };

  const logout = () => {
    setLoggedin(false);
  };

  return (
    <div className="container">
      <h2>React Private Routes Example</h2>
      <BrowserRouter>
        <NavBar />

        <Routes>
          <Route path="/" element={<Home />} />
          <Route
            path="/profile"
            element={
              <PrivateRoute isAuthenticated={isAuthenticated}>
                <Profile />
              </PrivateRoute>
            }
          />
          <Route
            path="/dashboard"
            element={
              <PrivateRoute isAuthenticated={isAuthenticated}>
                <Dashboard />
              </PrivateRoute>
            }
          />
        </Routes>

        {isAuthenticated ? (
          <div>
            <button className="btn-danger" onClick={logout}>
              Log out
            </button>
          </div>
        ) : (
          <div>
            <button className="btn-dark" onClick={login}>
              Log in
            </button>
          </div>
        )}
      </BrowserRouter>
    </div>
  );
}

Run Development Server

Head over to terminal, type the command and hit enter to invoke the react server, your app will be running on the mentioned url.

npm start
http://localhost:3000

How to Build Private Routes in React with React Router

Summary

In this tutorial, we have learned how to use the react-router v6 library to build Public and Private routes. How to create RouteSecure component and give access to authenticated users else redirect to a certain URL.

We have also answered how to redirect in react, how to check whether the user is logged in and how to secure multiple routes by accessing unauthorized users in React.