Implementing Protected Routes and Authentication with React Router

Almost every web application requires some form of authentication to prevent unauthorized users from having access to the inner workings of the applications.

For this tutorial, I’ll be showing how to set up an authentication route and protect other routes from being accessed by unauthorized users.

Protected routes or private routes are those routes that refrain unauthorized users from penetrating the React app’s pages. We will create a React app that will have certain pages that allow only those users who are authorized. So, we will formulate some components for associating to routes and keep a fake auth state. this state will return a boolean value; by default, it returns a null state. Based on this, we will allow users to navigate to private or public routes in React.

Installation

To get started with React Router, you need to install it in your project. You can do this using npm or yarn:

npm install react-router-dom    or yarn add react-router-dom

Implementing protected Routes

To use React Router effectively, we’ll start by creating some components within your React application. Following these steps:

  1. Create a folder: Within your project directory, create a folder named “components” inside the “src” folder.
  2. Create Component Files: Inside the “components” folder, define three example files named “Home.js,” “Product.js,” and “Dashboardt.js.”.
  3. Define Component Content

Now, let’s update the component code for each of these files:

Home.js:-

// Home.js import React from 'react'; function Home () {     return (         <h2>Welcome to the Home Page</h2>        );   }  export default Home;
Code language: JavaScript (javascript)

Product.js:-

// Product.js import React from 'react'; function Product () {     return (         <h2>Welcome to the Product Page</h2>        );   }  export default Product;
Code language: JavaScript (javascript)

Dashboard.js:-

// Dashboard.js import React from 'react'; Function Dashboard (){     Return (      <h2>Welcome to the Dashboard Page</h2>         ); } export default Dashboard;
Code language: JavaScript (javascript)

Design a Navigation Bar:

To facilitate navigation between different pages, create a `Navbar.js` inside the components folder that serves as a layout component for your application.

import React from "react"; import { Link } from 'react-router-dom' const Navbar= () => {   return (     <nav>      <ul>           <li>             <Link to="/">Home</Link>           </li>           <li>             <Link to="/product">Product</Link>           </li>           <li>             <Link to="/dashboard">Dashboard</Link>           </li>         </ul>     </nav>   ) } export default Navbar;
Code language: JavaScript (javascript)

Set Up Route Protection

Create a file named ‘Protected.js’ within the ‘components’ directory. Inside this file, define a function called ‘Protected’ that accepts two props: ‘isSignedIn,’ representing the authentication state (true if signed in, false if not), and ‘children,’ which represents the private route components. The ‘Protected’ function is designed to handle protected routes, allowing access only to authenticated users while rendering the specified child 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;
Code language: JavaScript (javascript)

Configuring Private Routes in App.js

import { useState } from 'react'; import { BrowserRouter, Routes, Route } from 'react-router-dom'; import Navbar from './components/Navbar'; import Home from './components/Home'; import Products from './components/Products'; import Dashboard from './components/Dashboard'; import Protected from './components/Protected'; export default function App() {   // State to track user authentication status (null represents not signed in).   const [isSignedIn, setIsSignedIn] = useState(null);   // Function to simulate user sign-in.   const signin = () => {     setIsSignedIn(true);   }   // Function to simulate user sign-out.   const signout = () => {     setIsSignedIn(false);   }   return (     <div>       <h2>React Protected Routes Example</h2>       <BrowserRouter>         < Navbar />         <Routes>           {/* Home route accessible to all users */}           <Route path="/" element={<Home />} />           {/* Dashboard and Products routes protected by the 'Protected' component */}           <Route             path="/dashboard"             element={               <Protected isSignedIn={isSignedIn}>                 <Dashboard />               </Protected>             }           />           <Route             path="/products"             element={               <Protected isSignedIn={isSignedIn}>                 <Products />               </Protected>             }           />         </Routes>         {/* Conditional rendering of sign-in/sign-out buttons */}         {isSignedIn ? (           <div >             <button onClick={signout}>               Sign out             </button>           </div>         ) : (           <div>             <button onClick={signin}>               Sign in             </button>           </div>         )}       </BrowserRouter>     </div>   ); }
Code language: PHP (php)

By simulating authentication with useState and protecting routes with the Protected component, this code demonstrates the basic concept of implementing protected routes in a React application. In a real project, the authentication logic would be more sophisticated and secure, but this example provides a foundation for understanding the key principles involved.

Conclusion

In this tutorial, we’ve delved into the world of protected routes in React applications using React Router. These protected routes are essential for securing your web app and ensuring that only authorized users can access specific parts of it. We started by creating key components and establishing a basic authentication state, providing a foundational understanding of real-world authentication systems. The ‘Protected’ component served as the parent of protected routes, allowing access exclusively to authenticated users. Armed with these core concepts, 

Recent Post

  • Generative AI in HR Operations: Overview, Use Cases, Challenges, and Future Trends

    Overview Imagine a workplace where HR tasks aren’t bogged down by endless paperwork or repetitive chores, but instead powered by intelligent systems that think, create, and adapt—welcome to the world of GenAI. Generative AI in HR operations offers a perfect blend of efficiency, personalization, and strategic insight that transforms how organizations interact with their talent. […]

  • Generative AI in Sales: Implementation Approaches, Use Cases, Challenges, Best Practices, and Future Trends

    The world of sales is evolving at lightning speed. Today’s sales teams are not just tasked with meeting ambitious quotas but must also navigate a maze of complex buyer journeys and ever-rising customer expectations. Despite relying on advanced CRM systems and various sales tools, many teams remain bogged down by repetitive administrative tasks, a lack […]

  • Generative AI in Due Diligence: Integration Approaches, Use Cases, Challenges, and Future Outlook

    Generative AI is revolutionizing the due diligence landscape, setting unprecedented benchmarks in data analysis, risk management, and operational efficiency. By combining advanced data processing capabilities with human-like contextual understanding, this cutting-edge technology is reshaping traditional due diligence processes, making them more efficient, accurate, and insightful. This comprehensive guide explores the integration strategies, practical applications, challenges, […]

  • Exploring the Role of AI in Sustainable Development Goals (SDGs)

    Artificial Intelligence (AI) is revolutionizing how we address some of the world’s most pressing challenges. As we strive to meet the United Nations’ Sustainable Development Goals (SDGs) by 2030, AI emerges as a powerful tool to accelerate progress across various domains. AI’s potential to contribute to sustainable development is vast from eradicating poverty to combating […]

  • Future Trends in AI Chatbots: What to Expect in the Next Decade

    Artificial Intelligence (AI) chatbots have become indispensable across industries. The absolute conversational capabilities of AI chatbots are enhancing customer engagement, streamlining operations, and transforming how businesses interact with users. As technology evolves, the future of AI chatbots holds revolutionary advancements that will redefine their capabilities. So, let’s start with exploring the AI chatbot trends: Future […]

  • Linguistics and NLP: Enhancing AI Chatbots for Multilingual Support

    In today’s interconnected world, businesses and individuals often communicate across linguistic boundaries. The growing need for seamless communication has driven significant advancements in artificial intelligence (AI), particularly in natural language processing (NLP) and linguistics. AI chatbots with multilingual support, are revolutionizing global customer engagement and service delivery. This blog explores how linguistics and NLP are […]

Click to Copy