Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
How to Integrate React Router with Remix?
Next article icon

How to Create a Protected Route with react-router-dom?

Last Updated : 31 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A protected route in a React application is a route that only authorized users can access. This is useful for securing parts of an application that should not be available to everyone. We will see how we can create a protected route with react-router-dom.

Prerequisites:

  • NPM & NodeJS
  • ReactJS

Steps to Setup ReactJS Application and Installing Required Modules

Step 1: Create a ReactJS application using the following command

npx create-react-app my-app

Step 2: Navigate to the Project directory

cd my-app

Step 3: Install the necessary packages/libraries in your project using the following commands

npm install react-router-dom

Project Structure:

Screenshot-(142)
Project Structure

The updated dependencies in package.json file will look like:

"dependencies": { 
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.3",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Approach to Create a Protected Route

  • Create an isAuthenticated state in the App component to track whether the user is logged in.
  • Inside the ProtectedRoute component in the App, add Route elements for its child components we want to keep protected.
  • Create a ProtectedRoute component that checks if the user is authenticated.
  • When a user is authenticated we will render the child routes using <Outlet /.> otherwise redirect the user to the login page using <Navigate to/>.
  • Create LoginPage where we will perform a simple hardcoded check for credentials.
  • If the credentials are correct, we call the login function and navigate the user to the Dashboard page using useNavigate.

Example: In this example, we have created a protected dashboard route which will be accessible only if the user is authenticated.

JavaScript
// App.js import React, { useState, useEffect } from 'react'; import { Route, Routes } from 'react-router-dom';  import { BrowserRouter } from 'react-router-dom' import Dashboard from './components/Dashboard'; import ProtectedRoute from './components/ProtectedRoute'; import LoginPage from './components/LoginPage'; const App = () => {     const [isAuthenticated, setIsAuthenticated] =                                  useState(false);      const login = () => {         setIsAuthenticated(true);     };      const logout = () => {         setIsAuthenticated(false);     };      return (         <BrowserRouter>             <Routes>                 <Route element={<ProtectedRoute isAuthenticated                                         ={isAuthenticated} />} >                     <Route path="dashboard"                             element={<Dashboard logout                                      ={logout} />} />                  </Route>                  <Route path="/"                         element={<LoginPage login                                  ={login} />} />              </Routes>         </BrowserRouter>     ); };  export default App; 
JavaScript
// ProtectedRoute.js import React from 'react' import { Navigate, Outlet } from 'react-router-dom'  const ProtectedRoute = (props) => {     // let auth={'token': false}     return (         props.isAuthenticated ?          <Outlet /> : <Navigate to="/" />     ) }  export default ProtectedRoute; 
JavaScript
// LoginPage.js import React, { useState } from 'react'; import { useNavigate } from 'react-router-dom';  const LoginPage = ({ login }) => {     const [userId, setUserId] = useState('');     const [pass, setPass] = useState('');     const navigate = useNavigate();      const handleLogin = () => {         if (userId === 'user' && pass === 'pass') {             login(userId, pass);             navigate('/dashboard');         }     };      return (         <div>             <h2>Login Page</h2>             <div>                 <input                     type="text"                     placeholder="User ID"                     value={userId}                     onChange={(e) =>                          setUserId(e.target.value)}                 />             </div>             <div>                 <input                     type="text"                     placeholder="Password"                     value={pass}                     onChange={(e) =>                          setPass(e.target.value)}                 />             </div>             <button onClick={handleLogin}>Login</button>         </div>     ); };  export default LoginPage; 
JavaScript
// Dashboard.js import React from 'react'; import { useNavigate } from 'react-router-dom';  const Dashboard = ({ logout }) => {     const navigate = useNavigate();      const handleLogout = () => {         logout();         navigate('/');     };      return (         <div>             <h2>Hello user welcome to Dashboard</h2>             <h3>This page is protected</h3><br />             <button onClick={handleLogout}>                 Logout             </button>         </div>     ); };  export default Dashboard; 

Step to Run Application: Run the application using the following command from the root directory of the project

npm start

Output:

prt
Output

Next Article
How to Integrate React Router with Remix?
author
yuvrajghule281
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • ReactJS-Router

Similar Reads

  • How to Create Custom Router with the help of React Router ?
    To create a custom Router using React Router, you can define a new component that utilizes the Router's 'BrowserRouter' along with 'Route' components to handle different paths and render corresponding components. Use 'Link' components for navigation within your application, providing a seamless rout
    3 min read
  • How to Integrate React Router with Remix?
    Integrating React Router with Remix includes the usage of Remix's integrated router abilities thinking that Remix already uses React Router as its foundation. However, if you want to go beyond number one routing and leverage several React Router's extra precise or advanced skills. You may integrate
    7 min read
  • What are Protected Routes in React JS ?
    In web development, security is critical when building React applications, especially those handling sensitive data or functionalities, it's crucial to restrict access to certain parts of the application to authorized users only. This is where protected routes come into play. In this article, we wil
    4 min read
  • How to handle Nested Routes in React Router ?
    React Router allows us to create a hierarchical structure where child components can be rendered within parent components, resulting in a seamless navigation flow. In this article, we will see how to handle nested Routes in React Router. Approach to handle Nested RoutesTo implement nested routes in
    3 min read
  • How to navigate to a parent route from a child route?
    In angular, a root component that serves as the parent component of all the components and the rest of the other components can be called a Child Component to the root component. This structure is in a form of a tree where a component that is the parent of a child lies above the child component and
    4 min read
  • React Router vs. React Router DOM
    Routing is a fundamental part of any web application. It allows users to move between pages or views. smoothly in traditional web development Routing involves mapping URLs to specific content or views on the server. These are the following topics that we are going to discuss: Table of Content What i
    4 min read
  • How To Secure a Vite-Powered React App?
    Securing a Vite-powered React app involves several best practices and strategies to protect your application from threats and vulnerabilities. Vite, a fast and modern frontend build tool, combined with React, provides a robust environment for building web applications, but it's important to ensure t
    4 min read
  • How to pass query parameters with a routerLink ?
    The task is to pass query parameters with a routerLink, for that we can use the property binding concept to reach the goal. Using property binding, we can bind queryParams property and can provide the required details in the object. What is Property Binding? It is a concept where we use square brack
    2 min read
  • Route Component in React Router
    React Router is a popular library used for managing routing in React applications. At its core lies the Route component, which plays a pivotal role in defining the relationship between URLs and corresponding components. In this article, we'll delve into the intricacies of the Route component, explor
    5 min read
  • How to Read the Current full URL with React?
    In React applications, it is often necessary to read the current full URL for various purposes, such as routing, conditional rendering, or logging. There are two common approaches to achieve this: using the window.location object and using the useLocation hook from react-router-dom. Prerequisites:NP
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences