React 18 Protected Routes with React Router v6 Tutorial

Last Updated on by in React JS

Protected Routes in React offer a secure mechanism to grant access to only authenticated users. Protected routes help secure precious information and data on your website.

In this tutorial, we will walk you through how to create protected routes in React using the React Router library.

Route Guard prevents unauthorized users from accessing secured resources on a system or website. For creating private routes in React, we will require: React functional components; React Router v6 package

To create a route guard in React, we will look at how to set up, configure, and protect routes using the React Router library. Protected routes, or private routes, are those routes that prevent unauthorized users from penetrating into the React app’s pages.

How to Create Private Protected Routes in React using React Router

  • Step 1: Create React App
  • Step 2: Install Required Modules
  • Step 3: Create Component Files
  • Step 4: Build Menu Bar
  • Step 5: Set Up Route Protection
  • Step 6: Configure Private Routes
  • Step 7: Start React App

Create React App

Use below command to install a React app:

npx create-react-app react-private-route

Head over to the folder that we created using the above command.

cd react-private-route

Install Required Modules

Open the command prompt, and type the given command to install the react-router-dom and bootstrap modules.

npm i react-router-dom bootstrap --legacy-peer-deps

Create Component Files

Head over to the app folder, then create the components/Home.js file with the given code.

import React from 'react'

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

export default Home

In this step you need to create and add the code in the components/Products.js file.

import React from 'react'

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

export default Products

Next, you have to make and add the code in the components/Dashboard.js 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

Build Menu Bar

Subsequently, we have to make the components/MenuBar.js file, here in this file use the Link module to create the routes.

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

const MenuBar = () => {
  return (
    <nav className="d-flex justify-content-center">
      <div className="p-2">
        <Link to="/">Home</Link>
      </div>
      <div className="p-2">
        <Link to="/products">Products</Link>
      </div>
      <div className="p-2">
        <Link to="/dashboard">Dashboard</Link>
      </div>
    </nav>
  )
}

export default MenuBar

Set Up Route Protection

Create the components/Protected.js file; the Protected function accepts the props, which returns the auth state and private route components.

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

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

export default Protected

Configure Private Routes

Head over to App.js file, next add the following code in the file.

import '../node_modules/bootstrap/dist/css/bootstrap.min.css'
import './App.css'
import { useState } from 'react'

import { BrowserRouter, Routes, Route } from 'react-router-dom'

import MenuBar from './components/MenuBar'
import Home from './components/Home'
import Dashboard from './components/Dashboard'
import Products from './components/Products'

import Protected from './components/Protected'

export default function App() {
  const [isSignedIn, setIsSignedIn] = useState(null)

  const signin = () => {
    setIsSignedIn(true)
  }

  const signout = () => {
    setIsSignedIn(false)
  }

  return (
    <div className="container mt-5">
      <h2 className="mb-5 text-center">React Protected Routes Example</h2>
      <BrowserRouter>
        <MenuBar />

        <Routes>
          <Route path="/" element={<Home />} />

          <Route
            path="/dashboard"
            element={
              <Protected isSignedIn={isSignedIn}>
                <Dashboard />
              </Protected>
            }
          />
          <Route
            path="/products"
            element={
              <Protected isSignedIn={isSignedIn}>
                <Products />
              </Protected>
            }
          />
        </Routes>

        {isSignedIn ? (
          <div className="d-grid mt-5">
            <button className="btn-danger" onClick={signout}>
              Sign out
            </button>
          </div>
        ) : (
          <div className="d-grid mt-5">
            <button className="btn-dark" onClick={signin}>
              Sign in
            </button>
          </div>
        )}
      </BrowserRouter>
    </div>
  )
}

Start React App

We have to start the react app and test the secured React web pages or routes.

npm start

React Protected Routes with React Router v6 Tutorial

Conclusion

Protected routes or private routes are those routes that refrain unauthorized users from penetrating into the React app. In this tutorial we have covered how to create private routes in React app using React Router package.

In this React-router-dom protected routes tutorial, we found the easiest, simplest and dynamic way to secure routes in the React js app.

Additionally, we learned to use React Router in React for managing routes or URLs.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.